-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
cjs.js
58 lines (44 loc) · 1.94 KB
/
cjs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import getExportBlock from './shared/getExportBlock.js';
import esModuleExport from './shared/esModuleExport.js';
export default function cjs ( bundle, magicString, { exportMode, intro, outro }, options ) {
intro = ( options.useStrict === false ? intro : `'use strict';\n\n${intro}` ) +
( exportMode === 'named' && options.legacy !== true ? `${esModuleExport}\n\n` : '' );
let needsInterop = false;
const varOrConst = bundle.varOrConst;
const interop = options.interop !== false;
// TODO handle empty imports, once they're supported
const importBlock = bundle.externalModules
.map( module => {
if ( interop && module.declarations.default ) {
if ( module.exportsNamespace ) {
return `${varOrConst} ${module.name} = require('${module.path}');` +
`\n${varOrConst} ${module.name}__default = ${module.name}['default'];`;
}
needsInterop = true;
if ( module.exportsNames ) {
return `${varOrConst} ${module.name} = require('${module.path}');` +
`\n${varOrConst} ${module.name}__default = _interopDefault(${module.name});`;
}
return `${varOrConst} ${module.name} = _interopDefault(require('${module.path}'));`;
} else {
const activated = Object.keys( module.declarations )
.filter( name => module.declarations[ name ].activated );
const needsVar = activated.length || module.reexported;
return needsVar ?
`${varOrConst} ${module.name} = require('${module.path}');` :
`require('${module.path}');`;
}
})
.join( '\n' );
if ( needsInterop ) {
intro += `function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\n`;
}
if ( importBlock ) {
intro += importBlock + '\n\n';
}
magicString.prepend( intro );
const exportBlock = getExportBlock( bundle, exportMode, 'module.exports =' );
if ( exportBlock ) magicString.append( '\n\n' + exportBlock );
if ( outro ) magicString.append( outro );
return magicString;
}