UNPKG

1.59 kBJavaScriptView Raw
1import { has } from '../utils/object';
2import { getName, quoteId, req } from '../utils/map-helpers';
3
4export default function umd ( bundle, magicString, exportMode, options ) {
5 const indentStr = magicString.getIndentString();
6
7 const globalNames = options.globals || {};
8
9 let amdDeps = bundle.externalModules.map( quoteId );
10 let cjsDeps = bundle.externalModules.map( req );
11 let globalDeps = bundle.externalModules.map( module => {
12 return has( globalNames, module.id ) ? globalNames[ module.id ] : module.name;
13 });
14
15 let args = bundle.externalModules.map( getName );
16
17 if ( exportMode === 'named' ) {
18 amdDeps.unshift( `'exports'` );
19 cjsDeps.unshift( `'exports'` );
20 globalDeps.unshift( `(global.${options.moduleName} = {})` );
21
22 args.unshift( 'exports' );
23 }
24
25 const amdParams =
26 ( has( options, 'moduleId' ) ? `['${options.moduleId}'], ` : `` ) +
27 ( amdDeps.length ? `[${amdDeps.join( ', ' )}], ` : `` );
28
29 const intro =
30 `(function (global, factory) {
31 typeof exports === 'object' && typeof module !== 'undefined' ? factory(${cjsDeps.join( ', ' )}) :
32 typeof define === 'function' && define.amd ? define(${amdParams}factory) :
33 factory(${globalDeps});
34 }(this, function (${args}) { 'use strict';
35
36 `.replace( /^\t\t/gm, '' ).replace( /^\t/gm, indentStr );
37
38 const exports = bundle.entryModule.exports;
39
40 const exportBlock = '\n\n' + Object.keys( exports ).map( name => {
41 return `exports.${name} = ${exports[name].localName};`;
42 }).join( '\n' );
43
44 return magicString
45 .append( exportBlock )
46 .trim()
47 .indent()
48 .append( '\n\n}));' )
49 .prepend( intro );
50}