Merge pull request #320 from sveltejs/gh-13

add development warnings for missing data properties
pull/322/head
Rich Harris 8 years ago committed by GitHub
commit a8d19839cd

@ -19,6 +19,10 @@ export default class Generator {
this.components = {};
this.events = {};
// track which properties are needed, so we can provide useful info
// in dev mode
this.expectedProperties = {};
this.elementDepth = 0;
this.code = new MagicString( source );
@ -99,6 +103,10 @@ export default class Generator {
}
});
dependencies.forEach( name => {
this.expectedProperties[ name ] = true;
});
return {
dependencies,
contexts: usedContexts,

@ -304,13 +304,32 @@ export default function dom ( parsed, source, options, names ) {
` );
}
const initialState = templateProperties.data ? `Object.assign( template.data(), options.data )` : `options.data || {}`;
const stateBlock = new CodeBuilder();
stateBlock.addLine(
`this._state = ${templateProperties.data ? `Object.assign( template.data(), options.data )` : `options.data || {}`};`
);
if ( templateProperties.computed ) {
stateBlock.addLine(
`applyComputations( this._state, this._state, {}, true );`
);
}
if ( options.dev ) {
Object.keys( generator.expectedProperties ).forEach( prop => {
stateBlock.addLine(
`if ( !( '${prop}' in this._state ) ) throw new Error( "Component was created without expected data property 'foo'" );`
);
});
}
builders.main.addBlock( deindent`
function ${name} ( options ) {
options = options || {};
${generator.usesRefs ? `\nthis.refs = {}` : ``}
this._state = ${initialState};${templateProperties.computed ? `\napplyComputations( this._state, this._state, {}, true );` : ``}
${stateBlock}
this._observers = {
pre: Object.create( null ),

@ -41,6 +41,7 @@ describe( 'generate', () => {
showCompiledCode = config.show;
compileOptions = config.compileOptions || {};
compileOptions.shared = shared;
compileOptions.dev = config.dev;
try {
const source = fs.readFileSync( `test/generator/${dir}/main.html`, 'utf-8' );
@ -79,6 +80,8 @@ describe( 'generate', () => {
throw err;
}
let unintendedError = null;
return env()
.then( window => {
// Put the constructor on window for testing
@ -91,6 +94,11 @@ describe( 'generate', () => {
data: config.data
});
if ( config.error ) {
unintendedError = true;
throw new Error( 'Expected a runtime error' );
}
if ( config.html ) {
assert.htmlEqual( target.innerHTML, config.html );
}
@ -103,8 +111,14 @@ describe( 'generate', () => {
}
})
.catch( err => {
if ( !config.show ) console.log( addLineNumbers( code ) ); // eslint-disable-line no-console
throw err;
if ( config.error && !unintendedError ) {
config.error( assert, err );
}
else {
if ( !config.show ) console.log( addLineNumbers( code ) ); // eslint-disable-line no-console
throw err;
}
});
});
}

@ -0,0 +1,7 @@
export default {
dev: true,
error ( assert, err ) {
assert.equal( err.message, `Component was created without expected data property 'foo'` );
}
};
Loading…
Cancel
Save