UNPKG

1.86 kBJavaScriptView Raw
1import { blank } from '../utils/object.js';
2import { getName } from '../utils/map-helpers.js';
3import getInteropBlock from './shared/getInteropBlock.js';
4import getExportBlock from './shared/getExportBlock.js';
5
6function setupNamespace ( keypath ) {
7 let parts = keypath.split( '.' ); // TODO support e.g. `foo['something-hyphenated']`?
8
9 parts.pop();
10
11 let acc = 'this';
12
13 return parts
14 .map( part => ( acc += `.${part}`, `${acc} = ${acc} || {};` ) )
15 .join( '\n' ) + '\n';
16}
17
18export default function iife ( bundle, magicString, { exportMode, indentString }, options ) {
19 const globalNames = options.globals || blank();
20 const name = options.moduleName;
21 const isNamespaced = name && ~name.indexOf( '.' );
22
23 let dependencies = bundle.externalModules.map( module => {
24 return globalNames[ module.id ] || module.name;
25 });
26
27 let args = bundle.externalModules.map( getName );
28
29 if ( exportMode !== 'none' && !name ) {
30 throw new Error( 'You must supply options.moduleName for IIFE bundles' );
31 }
32
33 if ( exportMode === 'named' ) {
34 dependencies.unshift( `(this.${name} = {})` );
35 args.unshift( 'exports' );
36 }
37
38 const useStrict = options.useStrict !== false ? ` 'use strict';` : ``;
39 let intro = `(function (${args}) {${useStrict}\n\n`;
40 let outro = `\n\n})(${dependencies});`;
41
42 if ( exportMode === 'default' ) {
43 intro = ( isNamespaced ? `this.` : `var ` ) + `${name} = ${intro}`;
44 }
45
46 if ( isNamespaced ) {
47 intro = setupNamespace( name ) + intro;
48 }
49
50 // var foo__default = 'default' in foo ? foo['default'] : foo;
51 const interopBlock = getInteropBlock( bundle );
52 if ( interopBlock ) magicString.prepend( interopBlock + '\n\n' );
53
54 const exportBlock = getExportBlock( bundle.entryModule, exportMode );
55 if ( exportBlock ) magicString.append( '\n\n' + exportBlock );
56
57 return magicString
58 .indent( indentString )
59 .prepend( intro )
60 .append( outro );
61}