1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const { ConcatSource, OriginalSource } = require("webpack-sources");
|
---|
9 | const ExternalModule = require("../ExternalModule");
|
---|
10 | const Template = require("../Template");
|
---|
11 | const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
|
---|
12 |
|
---|
13 | /** @typedef {import("webpack-sources").Source} Source */
|
---|
14 | /** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdCommentObject} LibraryCustomUmdCommentObject */
|
---|
15 | /** @typedef {import("../../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */
|
---|
16 | /** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
|
---|
17 | /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
|
---|
18 | /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
|
---|
19 | /** @typedef {import("../Compiler")} Compiler */
|
---|
20 | /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
|
---|
21 | /** @typedef {import("../ExternalModule").RequestRecord} RequestRecord */
|
---|
22 | /** @typedef {import("../util/Hash")} Hash */
|
---|
23 | /**
|
---|
24 | * @template T
|
---|
25 | * @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>}
|
---|
26 | * LibraryContext<T>
|
---|
27 | */
|
---|
28 |
|
---|
29 | /**
|
---|
30 | * @param {string[]} accessor the accessor to convert to path
|
---|
31 | * @returns {string} the path
|
---|
32 | */
|
---|
33 | const accessorToObjectAccess = accessor =>
|
---|
34 | accessor.map(a => `[${JSON.stringify(a)}]`).join("");
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * @param {string|undefined} base the path prefix
|
---|
38 | * @param {string|string[]} accessor the accessor
|
---|
39 | * @param {string=} joinWith the element separator
|
---|
40 | * @returns {string} the path
|
---|
41 | */
|
---|
42 | const accessorAccess = (base, accessor, joinWith = ", ") => {
|
---|
43 | const accessors = Array.isArray(accessor) ? accessor : [accessor];
|
---|
44 | return accessors
|
---|
45 | .map((_, idx) => {
|
---|
46 | const a = base
|
---|
47 | ? base + accessorToObjectAccess(accessors.slice(0, idx + 1))
|
---|
48 | : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1));
|
---|
49 | if (idx === accessors.length - 1) return a;
|
---|
50 | if (idx === 0 && base === undefined)
|
---|
51 | return `${a} = typeof ${a} === "object" ? ${a} : {}`;
|
---|
52 | return `${a} = ${a} || {}`;
|
---|
53 | })
|
---|
54 | .join(joinWith);
|
---|
55 | };
|
---|
56 |
|
---|
57 | /** @typedef {string | string[] | LibraryCustomUmdObject} UmdLibraryPluginName */
|
---|
58 |
|
---|
59 | /**
|
---|
60 | * @typedef {object} UmdLibraryPluginOptions
|
---|
61 | * @property {LibraryType} type
|
---|
62 | * @property {boolean=} optionalAmdExternalAsGlobal
|
---|
63 | */
|
---|
64 |
|
---|
65 | /**
|
---|
66 | * @typedef {object} UmdLibraryPluginParsed
|
---|
67 | * @property {string | string[] | undefined} name
|
---|
68 | * @property {LibraryCustomUmdObject} names
|
---|
69 | * @property {string | LibraryCustomUmdCommentObject | undefined} auxiliaryComment
|
---|
70 | * @property {boolean | undefined} namedDefine
|
---|
71 | */
|
---|
72 |
|
---|
73 | /**
|
---|
74 | * @typedef {UmdLibraryPluginParsed} T
|
---|
75 | * @extends {AbstractLibraryPlugin<UmdLibraryPluginParsed>}
|
---|
76 | */
|
---|
77 | class UmdLibraryPlugin extends AbstractLibraryPlugin {
|
---|
78 | /**
|
---|
79 | * @param {UmdLibraryPluginOptions} options the plugin option
|
---|
80 | */
|
---|
81 | constructor(options) {
|
---|
82 | super({
|
---|
83 | pluginName: "UmdLibraryPlugin",
|
---|
84 | type: options.type
|
---|
85 | });
|
---|
86 |
|
---|
87 | this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal;
|
---|
88 | }
|
---|
89 |
|
---|
90 | /**
|
---|
91 | * @param {LibraryOptions} library normalized library option
|
---|
92 | * @returns {T | false} preprocess as needed by overriding
|
---|
93 | */
|
---|
94 | parseOptions(library) {
|
---|
95 | /** @type {LibraryName | undefined} */
|
---|
96 | let name;
|
---|
97 | /** @type {LibraryCustomUmdObject} */
|
---|
98 | let names;
|
---|
99 | if (typeof library.name === "object" && !Array.isArray(library.name)) {
|
---|
100 | name = library.name.root || library.name.amd || library.name.commonjs;
|
---|
101 | names = library.name;
|
---|
102 | } else {
|
---|
103 | name = library.name;
|
---|
104 | const singleName = Array.isArray(name) ? name[0] : name;
|
---|
105 | names = {
|
---|
106 | commonjs: singleName,
|
---|
107 | root: library.name,
|
---|
108 | amd: singleName
|
---|
109 | };
|
---|
110 | }
|
---|
111 | return {
|
---|
112 | name,
|
---|
113 | names,
|
---|
114 | auxiliaryComment: library.auxiliaryComment,
|
---|
115 | namedDefine: library.umdNamedDefine
|
---|
116 | };
|
---|
117 | }
|
---|
118 |
|
---|
119 | /**
|
---|
120 | * @param {Source} source source
|
---|
121 | * @param {RenderContext} renderContext render context
|
---|
122 | * @param {LibraryContext<T>} libraryContext context
|
---|
123 | * @returns {Source} source with library export
|
---|
124 | */
|
---|
125 | render(
|
---|
126 | source,
|
---|
127 | { chunkGraph, runtimeTemplate, chunk, moduleGraph },
|
---|
128 | { options, compilation }
|
---|
129 | ) {
|
---|
130 | const modules = chunkGraph
|
---|
131 | .getChunkModules(chunk)
|
---|
132 | .filter(
|
---|
133 | m =>
|
---|
134 | m instanceof ExternalModule &&
|
---|
135 | (m.externalType === "umd" || m.externalType === "umd2")
|
---|
136 | );
|
---|
137 | let externals = /** @type {ExternalModule[]} */ (modules);
|
---|
138 | /** @type {ExternalModule[]} */
|
---|
139 | const optionalExternals = [];
|
---|
140 | /** @type {ExternalModule[]} */
|
---|
141 | let requiredExternals = [];
|
---|
142 | if (this.optionalAmdExternalAsGlobal) {
|
---|
143 | for (const m of externals) {
|
---|
144 | if (m.isOptional(moduleGraph)) {
|
---|
145 | optionalExternals.push(m);
|
---|
146 | } else {
|
---|
147 | requiredExternals.push(m);
|
---|
148 | }
|
---|
149 | }
|
---|
150 | externals = requiredExternals.concat(optionalExternals);
|
---|
151 | } else {
|
---|
152 | requiredExternals = externals;
|
---|
153 | }
|
---|
154 |
|
---|
155 | /**
|
---|
156 | * @param {string} str the string to replace
|
---|
157 | * @returns {string} the replaced keys
|
---|
158 | */
|
---|
159 | const replaceKeys = str =>
|
---|
160 | compilation.getPath(str, {
|
---|
161 | chunk
|
---|
162 | });
|
---|
163 |
|
---|
164 | /**
|
---|
165 | * @param {ExternalModule[]} modules external modules
|
---|
166 | * @returns {string} result
|
---|
167 | */
|
---|
168 | const externalsDepsArray = modules =>
|
---|
169 | `[${replaceKeys(
|
---|
170 | modules
|
---|
171 | .map(m =>
|
---|
172 | JSON.stringify(
|
---|
173 | typeof m.request === "object"
|
---|
174 | ? /** @type {RequestRecord} */
|
---|
175 | (m.request).amd
|
---|
176 | : m.request
|
---|
177 | )
|
---|
178 | )
|
---|
179 | .join(", ")
|
---|
180 | )}]`;
|
---|
181 |
|
---|
182 | /**
|
---|
183 | * @param {ExternalModule[]} modules external modules
|
---|
184 | * @returns {string} result
|
---|
185 | */
|
---|
186 | const externalsRootArray = modules =>
|
---|
187 | replaceKeys(
|
---|
188 | modules
|
---|
189 | .map(m => {
|
---|
190 | let request = m.request;
|
---|
191 | if (typeof request === "object")
|
---|
192 | request =
|
---|
193 | /** @type {RequestRecord} */
|
---|
194 | (request).root;
|
---|
195 | return `root${accessorToObjectAccess(/** @type {string[]} */ ([]).concat(request))}`;
|
---|
196 | })
|
---|
197 | .join(", ")
|
---|
198 | );
|
---|
199 |
|
---|
200 | /**
|
---|
201 | * @param {string} type the type
|
---|
202 | * @returns {string} external require array
|
---|
203 | */
|
---|
204 | const externalsRequireArray = type =>
|
---|
205 | replaceKeys(
|
---|
206 | externals
|
---|
207 | .map(m => {
|
---|
208 | let expr;
|
---|
209 | let request = m.request;
|
---|
210 | if (typeof request === "object") {
|
---|
211 | request =
|
---|
212 | /** @type {RequestRecord} */
|
---|
213 | (request)[type];
|
---|
214 | }
|
---|
215 | if (request === undefined) {
|
---|
216 | throw new Error(
|
---|
217 | `Missing external configuration for type:${type}`
|
---|
218 | );
|
---|
219 | }
|
---|
220 | expr = Array.isArray(request)
|
---|
221 | ? `require(${JSON.stringify(
|
---|
222 | request[0]
|
---|
223 | )})${accessorToObjectAccess(request.slice(1))}`
|
---|
224 | : `require(${JSON.stringify(request)})`;
|
---|
225 | if (m.isOptional(moduleGraph)) {
|
---|
226 | expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`;
|
---|
227 | }
|
---|
228 | return expr;
|
---|
229 | })
|
---|
230 | .join(", ")
|
---|
231 | );
|
---|
232 |
|
---|
233 | /**
|
---|
234 | * @param {ExternalModule[]} modules external modules
|
---|
235 | * @returns {string} arguments
|
---|
236 | */
|
---|
237 | const externalsArguments = modules =>
|
---|
238 | modules
|
---|
239 | .map(
|
---|
240 | m =>
|
---|
241 | `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
|
---|
242 | `${chunkGraph.getModuleId(m)}`
|
---|
243 | )}__`
|
---|
244 | )
|
---|
245 | .join(", ");
|
---|
246 |
|
---|
247 | /**
|
---|
248 | * @param {string| string[]} library library name
|
---|
249 | * @returns {string} stringified library name
|
---|
250 | */
|
---|
251 | const libraryName = library =>
|
---|
252 | JSON.stringify(
|
---|
253 | replaceKeys(
|
---|
254 | /** @type {string} */
|
---|
255 | (/** @type {string[]} */ ([]).concat(library).pop())
|
---|
256 | )
|
---|
257 | );
|
---|
258 |
|
---|
259 | let amdFactory;
|
---|
260 | if (optionalExternals.length > 0) {
|
---|
261 | const wrapperArguments = externalsArguments(requiredExternals);
|
---|
262 | const factoryArguments =
|
---|
263 | requiredExternals.length > 0
|
---|
264 | ? `${externalsArguments(requiredExternals)}, ${externalsRootArray(
|
---|
265 | optionalExternals
|
---|
266 | )}`
|
---|
267 | : externalsRootArray(optionalExternals);
|
---|
268 | amdFactory =
|
---|
269 | `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` +
|
---|
270 | ` return factory(${factoryArguments});\n` +
|
---|
271 | " }";
|
---|
272 | } else {
|
---|
273 | amdFactory = "factory";
|
---|
274 | }
|
---|
275 |
|
---|
276 | const { auxiliaryComment, namedDefine, names } = options;
|
---|
277 |
|
---|
278 | /**
|
---|
279 | * @param {keyof LibraryCustomUmdCommentObject} type type
|
---|
280 | * @returns {string} comment
|
---|
281 | */
|
---|
282 | const getAuxiliaryComment = type => {
|
---|
283 | if (auxiliaryComment) {
|
---|
284 | if (typeof auxiliaryComment === "string")
|
---|
285 | return `\t//${auxiliaryComment}\n`;
|
---|
286 | if (auxiliaryComment[type]) return `\t//${auxiliaryComment[type]}\n`;
|
---|
287 | }
|
---|
288 | return "";
|
---|
289 | };
|
---|
290 |
|
---|
291 | return new ConcatSource(
|
---|
292 | new OriginalSource(
|
---|
293 | `(function webpackUniversalModuleDefinition(root, factory) {\n${getAuxiliaryComment(
|
---|
294 | "commonjs2"
|
---|
295 | )} if(typeof exports === 'object' && typeof module === 'object')\n` +
|
---|
296 | ` module.exports = factory(${externalsRequireArray(
|
---|
297 | "commonjs2"
|
---|
298 | )});\n${getAuxiliaryComment(
|
---|
299 | "amd"
|
---|
300 | )} else if(typeof define === 'function' && define.amd)\n${
|
---|
301 | requiredExternals.length > 0
|
---|
302 | ? names.amd && namedDefine === true
|
---|
303 | ? ` define(${libraryName(names.amd)}, ${externalsDepsArray(
|
---|
304 | requiredExternals
|
---|
305 | )}, ${amdFactory});\n`
|
---|
306 | : ` define(${externalsDepsArray(requiredExternals)}, ${
|
---|
307 | amdFactory
|
---|
308 | });\n`
|
---|
309 | : names.amd && namedDefine === true
|
---|
310 | ? ` define(${libraryName(names.amd)}, [], ${amdFactory});\n`
|
---|
311 | : ` define([], ${amdFactory});\n`
|
---|
312 | }${
|
---|
313 | names.root || names.commonjs
|
---|
314 | ? `${getAuxiliaryComment(
|
---|
315 | "commonjs"
|
---|
316 | )} else if(typeof exports === 'object')\n` +
|
---|
317 | ` exports[${libraryName(
|
---|
318 | /** @type {string | string[]} */
|
---|
319 | (names.commonjs || names.root)
|
---|
320 | )}] = factory(${externalsRequireArray(
|
---|
321 | "commonjs"
|
---|
322 | )});\n${getAuxiliaryComment("root")} else\n` +
|
---|
323 | ` ${replaceKeys(
|
---|
324 | accessorAccess(
|
---|
325 | "root",
|
---|
326 | /** @type {string | string[]} */
|
---|
327 | (names.root || names.commonjs)
|
---|
328 | )
|
---|
329 | )} = factory(${externalsRootArray(externals)});\n`
|
---|
330 | : ` else {\n${
|
---|
331 | externals.length > 0
|
---|
332 | ? ` var a = typeof exports === 'object' ? factory(${externalsRequireArray(
|
---|
333 | "commonjs"
|
---|
334 | )}) : factory(${externalsRootArray(externals)});\n`
|
---|
335 | : " var a = factory();\n"
|
---|
336 | } for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n` +
|
---|
337 | " }\n"
|
---|
338 | }})(${runtimeTemplate.outputOptions.globalObject}, ${
|
---|
339 | runtimeTemplate.supportsArrowFunction()
|
---|
340 | ? `(${externalsArguments(externals)}) =>`
|
---|
341 | : `function(${externalsArguments(externals)})`
|
---|
342 | } {\nreturn `,
|
---|
343 | "webpack/universalModuleDefinition"
|
---|
344 | ),
|
---|
345 | source,
|
---|
346 | ";\n})"
|
---|
347 | );
|
---|
348 | }
|
---|
349 | }
|
---|
350 |
|
---|
351 | module.exports = UmdLibraryPlugin;
|
---|