UNPKG

1.95 kBJavaScriptView Raw
1import { keys } from '../utils/object.js';
2
3function notDefault ( name ) {
4 return name !== 'default';
5}
6
7export default function es6 ( bundle, magicString ) {
8 const importBlock = bundle.externalModules
9 .map( module => {
10 const specifiers = [];
11 const specifiersList = [specifiers];
12 const importedNames = keys( module.declarations )
13 .filter( name => name !== '*' && name !== 'default' );
14
15 if ( module.declarations.default ) {
16 specifiers.push( module.name );
17 }
18
19 const namespaceSpecifier = module.declarations['*'] ? `* as ${module.name}` : null;
20 const namedSpecifier = importedNames.length ? `{ ${importedNames.join( ', ' )} }` : null;
21
22 if ( namespaceSpecifier && namedSpecifier ) {
23 // Namespace and named specifiers cannot be combined.
24 specifiersList.push( [namespaceSpecifier] );
25 specifiers.push( namedSpecifier );
26 } else if ( namedSpecifier ) {
27 specifiers.push( namedSpecifier );
28 } else if ( namespaceSpecifier ) {
29 specifiers.push( namespaceSpecifier );
30 }
31
32 return specifiersList
33 .map( specifiers =>
34 specifiers.length ?
35 `import ${specifiers.join( ', ' )} from '${module.id}';` :
36 `import '${module.id}';`
37 )
38 .join( '\n' );
39 })
40 .join( '\n' );
41
42 if ( importBlock ) {
43 magicString.prepend( importBlock + '\n\n' );
44 }
45
46 const module = bundle.entryModule;
47
48 const specifiers = module.getExports().filter( notDefault ).map( name => {
49 const declaration = module.traceExport( name );
50
51 return declaration.name === name ?
52 name :
53 `${declaration.name} as ${name}`;
54 });
55
56 let exportBlock = specifiers.length ? `export { ${specifiers.join(', ')} };` : '';
57
58 const defaultExport = module.exports.default || module.reexports.default;
59 if ( defaultExport ) {
60 exportBlock += `export default ${module.traceExport( 'default' ).render( true )};`;
61 }
62
63 if ( exportBlock ) {
64 magicString.append( '\n\n' + exportBlock.trim() );
65 }
66
67 return magicString.trim();
68}