UNPKG

1.45 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
6export default function iife ( bundle, magicString, { exportMode, indentString }, options ) {
7 const globalNames = options.globals || blank();
8
9 let dependencies = bundle.externalModules.map( module => {
10 return globalNames[ module.id ] || module.name;
11 });
12
13 let args = bundle.externalModules.map( getName );
14
15 if ( exportMode !== 'none' && !options.moduleName ) {
16 throw new Error( 'You must supply options.moduleName for IIFE bundles' );
17 }
18
19 if ( exportMode === 'named' ) {
20 dependencies.unshift( `(this.${options.moduleName} = {})` );
21 args.unshift( 'exports' );
22 }
23
24 const useStrict = options.useStrict !== false ? ` 'use strict';` : ``;
25 let intro = `(function (${args}) {${useStrict}\n\n`;
26 let outro = `\n\n})(${dependencies});`;
27
28 if ( exportMode === 'default' ) {
29 intro = `var ${options.moduleName} = ${intro}`;
30 }
31
32 // var foo__default = 'default' in foo ? foo['default'] : foo;
33 const interopBlock = getInteropBlock( bundle );
34 if ( interopBlock ) magicString.prepend( interopBlock + '\n\n' );
35
36 const exportBlock = getExportBlock( bundle.entryModule, exportMode );
37 if ( exportBlock ) magicString.append( '\n\n' + exportBlock );
38
39 return magicString
40 .indent( indentString )
41 .prepend( intro )
42 .append( outro );
43}