Browse Source

deconflict auto-generated default export names, convert expressions to declarations. fixes #29

contingency-plan
Rich-Harris 10 years ago
parent
commit
f031ccc53a
  1. 5
      src/Bundle.js
  2. 18
      src/Module.js
  3. 3
      test/function/default-function-export-conflict/_config.js
  4. 7
      test/function/default-function-export-conflict/foo.js
  5. 3
      test/function/default-function-export-conflict/main.js

5
src/Bundle.js

@ -291,8 +291,13 @@ export default class Bundle {
return;
}
// anonymous functions should be converted into declarations
if ( statement.node.declaration.type === 'FunctionExpression' ) {
source.overwrite( statement.node.start, statement.node.declaration.start + 8, `function ${canonicalName}` );
} else {
source.overwrite( statement.node.start, statement.node.declaration.start, `var ${canonicalName} = ` );
}
}
else {
throw new Error( 'Unhandled export' );

18
src/Module.js

@ -127,6 +127,8 @@ export default class Module {
// export default 42;
if ( node.type === 'ExportDefaultDeclaration' ) {
const isDeclaration = /Declaration$/.test( node.declaration.type );
const isAnonymous = /(?:Class|Function)Expression$/.test( node.declaration.type );
const declaredName = isDeclaration && node.declaration.id.name;
const identifier = node.declaration.type === 'Identifier' && node.declaration.name;
@ -137,6 +139,7 @@ export default class Module {
declaredName,
identifier,
isDeclaration,
isAnonymous,
isModified: false // in case of `export default foo; foo = somethingElse`
};
}
@ -464,9 +467,18 @@ export default class Module {
this.canonicalNames[ name ] = replacement;
}
suggestName ( exportName, suggestion ) {
if ( !this.suggestedNames[ exportName ] ) {
this.suggestedNames[ exportName ] = makeLegalIdentifier( suggestion );
suggestName ( defaultOrBatch, suggestion ) {
// deconflict anonymous default exports with this module's definitions
const shouldDeconflict = this.exports.default && this.exports.default.isAnonymous;
if ( shouldDeconflict ) {
while ( suggestion in this.definitions ) {
suggestion = `_${suggestion}`;
}
}
if ( !this.suggestedNames[ defaultOrBatch ] ) {
this.suggestedNames[ defaultOrBatch ] = makeLegalIdentifier( suggestion );
}
}
}

3
test/function/default-function-export-conflict/_config.js

@ -0,0 +1,3 @@
module.exports = {
description: 'default export of anonymous function'
};

7
test/function/default-function-export-conflict/foo.js

@ -0,0 +1,7 @@
function foo() {
return 42;
}
export default function () {
return foo();
}

3
test/function/default-function-export-conflict/main.js

@ -0,0 +1,3 @@
import foo from './foo';
assert.equal( foo(), 42 );
Loading…
Cancel
Save