1 | import { blank } from '../utils/object.js';
|
2 | import { getName, quoteId, req } from '../utils/map-helpers.js';
|
3 | import getInteropBlock from './shared/getInteropBlock.js';
|
4 | import getExportBlock from './shared/getExportBlock.js';
|
5 |
|
6 | export default function umd ( bundle, magicString, { exportMode, indentString }, options ) {
|
7 | if ( exportMode !== 'none' && !options.moduleName ) {
|
8 | throw new Error( 'You must supply options.moduleName for UMD bundles' );
|
9 | }
|
10 |
|
11 | const globalNames = options.globals || blank();
|
12 |
|
13 | let amdDeps = bundle.externalModules.map( quoteId );
|
14 | let cjsDeps = bundle.externalModules.map( req );
|
15 | let globalDeps = bundle.externalModules.map( module => {
|
16 | return 'global.' + (globalNames[ module.id ] || module.name);
|
17 | });
|
18 |
|
19 | let args = bundle.externalModules.map( getName );
|
20 |
|
21 | if ( exportMode === 'named' ) {
|
22 | amdDeps.unshift( `'exports'` );
|
23 | cjsDeps.unshift( `exports` );
|
24 | globalDeps.unshift( `(global.${options.moduleName} = {})` );
|
25 |
|
26 | args.unshift( 'exports' );
|
27 | }
|
28 |
|
29 | const amdParams =
|
30 | ( options.moduleId ? `'${options.moduleId}', ` : `` ) +
|
31 | ( amdDeps.length ? `[${amdDeps.join( ', ' )}], ` : `` );
|
32 |
|
33 | const cjsExport = exportMode === 'default' ? `module.exports = ` : ``;
|
34 | const defaultExport = exportMode === 'default' ? `global.${options.moduleName} = ` : '';
|
35 |
|
36 | const useStrict = options.useStrict !== false ? ` 'use strict';` : ``;
|
37 |
|
38 | const intro =
|
39 | `(function (global, factory) {
|
40 | typeof exports === 'object' && typeof module !== 'undefined' ? ${cjsExport}factory(${cjsDeps.join( ', ' )}) :
|
41 | typeof define === 'function' && define.amd ? define(${amdParams}factory) :
|
42 | ${defaultExport}factory(${globalDeps});
|
43 | }(this, function (${args}) {${useStrict}
|
44 |
|
45 | `.replace( /^\t\t/gm, '' ).replace( /^\t/gm, magicString.getIndentString() );
|
46 |
|
47 |
|
48 | const interopBlock = getInteropBlock( bundle );
|
49 | if ( interopBlock ) magicString.prepend( interopBlock + '\n\n' );
|
50 |
|
51 | const exportBlock = getExportBlock( bundle.entryModule, exportMode );
|
52 | if ( exportBlock ) magicString.append( '\n\n' + exportBlock );
|
53 |
|
54 | return magicString
|
55 | .trim()
|
56 | .indent( indentString )
|
57 | .append( '\n\n}));' )
|
58 | .prepend( intro );
|
59 | }
|