forked from rollup/rollup
/
umd.ts
213 lines (194 loc) · 6.3 KB
/
umd.ts
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import type { Bundle, Bundle as MagicStringBundle } from 'magic-string';
import type { NormalizedOutputOptions } from '../rollup/types';
import { error } from '../utils/error';
import type { GenerateCodeSnippets } from '../utils/generateCodeSnippets';
import getCompleteAmdId from './shared/getCompleteAmdId';
import { getExportBlock, getNamespaceMarkers } from './shared/getExportBlock';
import getInteropBlock from './shared/getInteropBlock';
import removeExtensionFromRelativeAmdId from './shared/removeExtensionFromRelativeAmdId';
import { keypath } from './shared/sanitize';
import { assignToDeepVariable } from './shared/setupNamespace';
import trimEmptyImports from './shared/trimEmptyImports';
import warnOnBuiltins from './shared/warnOnBuiltins';
import type { FinaliserOptions } from './index';
function globalProp(name: string, globalVar: string, getPropertyAccess: (name: string) => string) {
if (!name) return 'null';
return `${globalVar}${keypath(name, getPropertyAccess)}`;
}
function safeAccess(
name: string,
globalVar: string,
{ _, getPropertyAccess }: GenerateCodeSnippets
) {
let propertyPath = globalVar;
return name
.split('.')
.map(part => (propertyPath += getPropertyAccess(part)))
.join(`${_}&&${_}`);
}
export default function umd(
magicString: MagicStringBundle,
{
accessedGlobals,
dependencies,
exports,
hasExports,
id,
indent: t,
intro,
namedExportsMode,
outro,
snippets,
warn
}: FinaliserOptions,
{
amd,
compact,
esModule,
extend,
externalLiveBindings,
freeze,
interop,
name,
namespaceToStringTag,
globals,
noConflict,
strict
}: NormalizedOutputOptions
): Bundle {
const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
const factoryVar = compact ? 'f' : 'factory';
const globalVar = compact ? 'g' : 'global';
if (hasExports && !name) {
return error({
code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
message:
'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
});
}
warnOnBuiltins(warn, dependencies);
const amdDeps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
const cjsDeps = dependencies.map(m => `require('${m.id}')`);
const trimmedImports = trimEmptyImports(dependencies);
const globalDeps = trimmedImports.map(module =>
globalProp(module.globalName, globalVar, getPropertyAccess)
);
const factoryParams = trimmedImports.map(m => m.name);
if (namedExportsMode && (hasExports || noConflict)) {
amdDeps.unshift(`'exports'`);
cjsDeps.unshift(`exports`);
globalDeps.unshift(
assignToDeepVariable(
name!,
globalVar,
globals,
`${extend ? `${globalProp(name!, globalVar, getPropertyAccess)}${_}||${_}` : ''}{}`,
snippets
)
);
factoryParams.unshift('exports');
}
const completeAmdId = getCompleteAmdId(amd, id);
const amdParams =
(completeAmdId ? `'${completeAmdId}',${_}` : ``) +
(amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
const define = amd.define;
const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
const useStrict = strict ? `${_}'use strict';${n}` : ``;
let iifeExport;
if (noConflict) {
const noConflictExportsVar = compact ? 'e' : 'exports';
let factory;
if (!namedExportsMode && hasExports) {
factory = `${cnst} ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(
name!,
globalVar,
globals,
`${factoryVar}(${globalDeps.join(`,${_}`)})`,
snippets
)};`;
} else {
const module = globalDeps.shift();
factory =
`${cnst} ${noConflictExportsVar}${_}=${_}${module};${n}` +
`${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
}
iifeExport =
`(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
`${t}${t}${cnst} current${_}=${_}${safeAccess(name!, globalVar, snippets)};${n}` +
`${t}${t}${factory}${n}` +
`${t}${t}${noConflictExportsVar}.noConflict${_}=${_}${getFunctionIntro([], {
isAsync: false,
name: null
})}{${_}` +
`${globalProp(
name!,
globalVar,
getPropertyAccess
)}${_}=${_}current;${_}return ${noConflictExportsVar}${s}${_}};${n}` +
`${t}})()`;
} else {
iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
if (!namedExportsMode && hasExports) {
iifeExport = assignToDeepVariable(name!, globalVar, globals, iifeExport, snippets);
}
}
const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
const wrapperParams: string[] = [factoryVar];
if (iifeNeedsGlobal) {
wrapperParams.unshift(globalVar);
}
const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
const iifeStart = iifeNeedsGlobal
? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
: '';
const iifeEnd = iifeNeedsGlobal ? ')' : '';
const cjsIntro = iifeNeedsGlobal
? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
`${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
: '';
const wrapperIntro =
`(${getNonArrowFunctionIntro(wrapperParams, { isAsync: false, name: null })}{${n}` +
cjsIntro +
`${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
`${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
// factory function should be wrapped by parentheses to avoid lazy parsing,
// cf. https://v8.dev/blog/preparser#pife
`})(${globalArg}(${getNonArrowFunctionIntro(factoryParams, {
isAsync: false,
name: null
})}{${useStrict}${n}`;
const wrapperOutro = n + n + '}));';
magicString.prepend(
`${intro}${getInteropBlock(
dependencies,
interop,
externalLiveBindings,
freeze,
namespaceToStringTag,
accessedGlobals,
t,
snippets
)}`
);
const exportBlock = getExportBlock(
exports,
dependencies,
namedExportsMode,
interop,
snippets,
t,
externalLiveBindings
);
let namespaceMarkers = getNamespaceMarkers(
namedExportsMode && hasExports,
esModule,
namespaceToStringTag,
snippets
);
if (namespaceMarkers) {
namespaceMarkers = n + n + namespaceMarkers;
}
magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
}