Browse Source

refactore some stuff

contingency-plan
Rich Harris 10 years ago
parent
commit
838f0a8812
  1. 15
      src/Bundle.js
  2. 10
      src/ExternalModule.js
  3. 103
      src/Module.js
  4. 2
      src/finalisers/cjs.js
  5. 11
      src/utils/makeLegalIdentifier.js

15
src/Bundle.js

@ -26,6 +26,7 @@ export default class Bundle {
this.statements = []; this.statements = [];
this.externalModules = []; this.externalModules = [];
this.defaultExportName = null; this.defaultExportName = null;
this.internalNamespaceModules = [];
} }
fetchModule ( importee, importer ) { fetchModule ( importee, importer ) {
@ -96,7 +97,7 @@ export default class Bundle {
defaultExportName = `_${defaultExportName}`; defaultExportName = `_${defaultExportName}`;
} }
this.defaultExportName = defaultExportName; entryModule.suggestedNames.default = defaultExportName;
node._source.overwrite( node.start, node.declaration.start, `var ${defaultExportName} = ` ); node._source.overwrite( node.start, node.declaration.start, `var ${defaultExportName} = ` );
} }
@ -184,6 +185,18 @@ export default class Bundle {
magicString.addSource( source ); magicString.addSource( source );
}); });
// prepend bundle with internal namespaces
const indentString = magicString.getIndentString();
const namespaceBlock = this.internalNamespaceModules.map( module => {
const exportKeys = keys( module.exports );
return `var ${module.suggestedNames['*']} = {\n` +
exportKeys.map( key => `${indentString}get ${key} () { return ${module.getCanonicalName(key)}; }` ).join( ',\n' ) +
`\n};\n\n`;
}).join( '' );
magicString.prepend( namespaceBlock );
const finalise = finalisers[ options.format || 'es6' ]; const finalise = finalisers[ options.format || 'es6' ];
if ( !finalise ) { if ( !finalise ) {

10
src/ExternalModule.js

@ -7,7 +7,7 @@ export default class ExternalModule {
this.importedByBundle = []; this.importedByBundle = [];
this.canonicalNames = {}; this.canonicalNames = {};
this.defaultExportName = null; this.suggestedNames = {};
this.needsDefault = null; this.needsDefault = null;
this.needsNamed = null; this.needsNamed = null;
@ -30,9 +30,9 @@ export default class ExternalModule {
this.canonicalNames[ name ] = replacement; this.canonicalNames[ name ] = replacement;
} }
suggestDefaultName ( name ) { suggestName ( exportName, suggestion ) {
if ( !this.defaultExportName ) { if ( !this.suggestedNames[ exportName ] ) {
this.defaultExportName = name; this.suggestedNames[ exportName ] = suggestion;
} }
} }
} }

103
src/Module.js

@ -6,6 +6,7 @@ import analyse from './ast/analyse';
import { has } from './utils/object'; import { has } from './utils/object';
import { sequence } from './utils/promise'; import { sequence } from './utils/promise';
import getLocation from './utils/getLocation'; import getLocation from './utils/getLocation';
import makeLegalIdentifier from './utils/makeLegalIdentifier';
const emptyArrayPromise = Promise.resolve([]); const emptyArrayPromise = Promise.resolve([]);
@ -19,6 +20,8 @@ export default class Module {
filename: path filename: path
}); });
this.suggestedNames = {};
try { try {
this.ast = parse( code, { this.ast = parse( code, {
ecmaVersion: 6, ecmaVersion: 6,
@ -160,27 +163,41 @@ export default class Module {
} }
getCanonicalName ( name ) { getCanonicalName ( name ) {
if ( has( this.imports, name ) ) { if ( has( this.suggestedNames, name ) ) {
const importDeclaration = this.imports[ name ]; name = this.suggestedNames[ name ];
const module = importDeclaration.module; }
if ( !has( this.canonicalNames, name ) ) {
let canonicalName;
let exporterLocalName; if ( has( this.imports, name ) ) {
const importDeclaration = this.imports[ name ];
const module = importDeclaration.module;
if ( importDeclaration.name === '*' ) {
canonicalName = module.suggestedNames[ '*' ];
} else {
let exporterLocalName;
if ( module.isExternal ) {
exporterLocalName = importDeclaration.name;
} else {
const exportDeclaration = module.exports[ importDeclaration.name ];
exporterLocalName = exportDeclaration.localName;
}
if ( module.isExternal ) { canonicalName = module.getCanonicalName( exporterLocalName );
exporterLocalName = importDeclaration.name; }
} else {
const exportDeclaration = module.exports[ importDeclaration.name ];
exporterLocalName = exportDeclaration.localName;
} }
return module.getCanonicalName( exporterLocalName ); else {
} canonicalName = name;
}
if ( name === 'default' ) { this.canonicalNames[ name ] = canonicalName;
name = this.defaultExportName;
} }
return has( this.canonicalNames, name ) ? this.canonicalNames[ name ] : name; return this.canonicalNames[ name ];
} }
define ( name ) { define ( name ) {
@ -200,7 +217,7 @@ export default class Module {
importDeclaration.module = module; importDeclaration.module = module;
if ( importDeclaration.name === 'default' ) { if ( importDeclaration.name === 'default' ) {
module.suggestDefaultName( importDeclaration.localName ); module.suggestName( 'default', importDeclaration.localName );
} }
if ( module.isExternal ) { if ( module.isExternal ) {
@ -214,6 +231,17 @@ export default class Module {
return emptyArrayPromise; return emptyArrayPromise;
} }
if ( importDeclaration.name === '*' ) {
module.suggestName( '*', importDeclaration.localName );
// we need to create an internal namespace
if ( !~this.bundle.internalNamespaceModules.indexOf( module ) ) {
this.bundle.internalNamespaceModules.push( module );
}
return module.includeAllStatements();
}
const exportDeclaration = module.exports[ importDeclaration.name ]; const exportDeclaration = module.exports[ importDeclaration.name ];
if ( !exportDeclaration ) { if ( !exportDeclaration ) {
@ -237,7 +265,7 @@ export default class Module {
if ( name === 'default' ) { if ( name === 'default' ) {
// We have an expression, e.g. `export default 42`. We have // We have an expression, e.g. `export default 42`. We have
// to assign that expression to a variable // to assign that expression to a variable
const replacement = this.defaultExportName; const replacement = this.suggestedNames.default;
statement = this.exports.default.node; statement = this.exports.default.node;
@ -316,13 +344,50 @@ export default class Module {
return this.definitionPromises[ name ]; return this.definitionPromises[ name ];
} }
includeAllStatements () {
return this.ast.body.filter( statement => {
// skip already-included statements
if ( statement._included ) return false;
// skip import declarations
if ( /^Import/.test( statement.type ) ) return false;
// skip `export { foo, bar, baz }`
if ( statement.type === 'ExportNamedDeclaration' && statement.specifiers.length ) return false;
// include everything else
// modify exports as necessary
if ( /^Export/.test( statement.type ) ) {
// remove `export` from `export var foo = 42`
if ( statement.type === 'ExportNamedDeclaration' && statement.declaration.type === 'VariableDeclaration' ) {
statement._source.remove( statement.start, statement.declaration.start );
}
// remove `export` from `export class Foo {...}` or `export default Foo`
else if ( statement.declaration.id ) {
statement._source.remove( statement.start, statement.declaration.start );
}
// declare variables for expressions
else {
statement._source.overwrite( statement.start, statement.declaration.start, `var TODO = ` );
}
}
return true;
});
}
rename ( name, replacement ) { rename ( name, replacement ) {
this.canonicalNames[ name ] = replacement; this.canonicalNames[ name ] = replacement;
} }
suggestDefaultName ( name ) { suggestName ( exportName, suggestion ) {
if ( !this.defaultExportName ) { if ( !this.suggestedNames[ exportName ] ) {
this.defaultExportName = name; this.suggestedNames[ exportName ] = makeLegalIdentifier( suggestion );
} }
} }
} }

2
src/finalisers/cjs.js

@ -26,7 +26,7 @@ export default function cjs ( bundle, magicString, exportMode ) {
let exportBlock; let exportBlock;
if ( exportMode === 'default' && bundle.entryModule.exports.default ) { if ( exportMode === 'default' && bundle.entryModule.exports.default ) {
exportBlock = `module.exports = ${bundle.defaultExportName};`; exportBlock = `module.exports = ${bundle.entryModule.suggestedNames.default};`;
} else if ( exportMode === 'named' ) { } else if ( exportMode === 'named' ) {
exportBlock = keys( bundle.entryModule.exports ) exportBlock = keys( bundle.entryModule.exports )
.map( key => { .map( key => {

11
src/utils/makeLegalIdentifier.js

@ -1,6 +1,13 @@
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split( ' ' );
const builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split( ' ' );
let blacklisted = {};
reservedWords.concat( builtins ).forEach( word => blacklisted[ word ] = true );
export default function makeLegalIdentifier ( str ) { export default function makeLegalIdentifier ( str ) {
str = str.replace( /[^$_a-zA-Z0-9]/g, '_' ); str = str.replace( /[^$_a-zA-Z0-9]/g, '_' );
if ( /\d/.test( str[0] ) ) str = `_${str}`; if ( /\d/.test( str[0] ) || blacklisted[ str ] ) str = `_${str}`;
return str; return str;
} }

Loading…
Cancel
Save