webpack 5.65.0 → 5.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of webpack might be problematic. Click here for more details.

Files changed (60) hide show
  1. package/lib/CacheFacade.js +2 -9
  2. package/lib/Chunk.js +2 -0
  3. package/lib/Compilation.js +79 -38
  4. package/lib/Dependency.js +10 -0
  5. package/lib/DependencyTemplate.js +9 -0
  6. package/lib/ExternalModule.js +92 -52
  7. package/lib/Generator.js +2 -0
  8. package/lib/Module.js +24 -1
  9. package/lib/ModuleFilenameHelpers.js +5 -1
  10. package/lib/NormalModule.js +3 -1
  11. package/lib/RuntimeGlobals.js +11 -1
  12. package/lib/RuntimePlugin.js +25 -0
  13. package/lib/RuntimeTemplate.js +21 -0
  14. package/lib/Template.js +2 -1
  15. package/lib/Watching.js +1 -1
  16. package/lib/WebpackOptionsApply.js +43 -2
  17. package/lib/asset/AssetGenerator.js +3 -1
  18. package/lib/asset/RawDataUrlModule.js +145 -0
  19. package/lib/config/defaults.js +59 -3
  20. package/lib/css/CssGenerator.js +106 -0
  21. package/lib/css/CssLoadingRuntimeModule.js +393 -0
  22. package/lib/css/CssModulesPlugin.js +444 -0
  23. package/lib/css/CssParser.js +618 -0
  24. package/lib/css/walkCssTokens.js +659 -0
  25. package/lib/dependencies/CssExportDependency.js +85 -0
  26. package/lib/dependencies/CssImportDependency.js +75 -0
  27. package/lib/dependencies/CssLocalIdentifierDependency.js +119 -0
  28. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +101 -0
  29. package/lib/dependencies/CssUrlDependency.js +132 -0
  30. package/lib/dependencies/URLDependency.js +3 -8
  31. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +1 -1
  32. package/lib/hmr/lazyCompilationBackend.js +3 -1
  33. package/lib/javascript/JavascriptGenerator.js +1 -0
  34. package/lib/javascript/StartupHelpers.js +3 -3
  35. package/lib/library/AssignLibraryPlugin.js +26 -3
  36. package/lib/library/EnableLibraryPlugin.js +11 -0
  37. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +1 -1
  38. package/lib/node/RequireChunkLoadingRuntimeModule.js +1 -1
  39. package/lib/optimize/ConcatenatedModule.js +10 -4
  40. package/lib/util/hash/xxhash64.js +2 -2
  41. package/lib/util/internalSerializables.js +11 -0
  42. package/lib/web/JsonpChunkLoadingRuntimeModule.js +2 -2
  43. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +1 -1
  44. package/package.json +2 -2
  45. package/schemas/WebpackOptions.check.js +1 -1
  46. package/schemas/WebpackOptions.json +55 -1
  47. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  48. package/schemas/plugins/container/ContainerPlugin.json +2 -1
  49. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  50. package/schemas/plugins/container/ContainerReferencePlugin.json +1 -0
  51. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  52. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  53. package/schemas/plugins/container/ModuleFederationPlugin.json +3 -1
  54. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +7 -0
  55. package/schemas/plugins/css/CssGeneratorOptions.check.js +6 -0
  56. package/schemas/plugins/css/CssGeneratorOptions.json +3 -0
  57. package/schemas/plugins/css/CssParserOptions.check.d.ts +7 -0
  58. package/schemas/plugins/css/CssParserOptions.check.js +6 -0
  59. package/schemas/plugins/css/CssParserOptions.json +3 -0
  60. package/types.d.ts +86 -2
@@ -0,0 +1,393 @@
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 { SyncWaterfallHook } = require("tapable");
9
+ const Compilation = require("../Compilation");
10
+ const RuntimeGlobals = require("../RuntimeGlobals");
11
+ const RuntimeModule = require("../RuntimeModule");
12
+ const Template = require("../Template");
13
+ const compileBooleanMatcher = require("../util/compileBooleanMatcher");
14
+ const { chunkHasCss } = require("./CssModulesPlugin");
15
+
16
+ /** @typedef {import("../Chunk")} Chunk */
17
+
18
+ /**
19
+ * @typedef {Object} JsonpCompilationPluginHooks
20
+ * @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet
21
+ */
22
+
23
+ /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
24
+ const compilationHooksMap = new WeakMap();
25
+
26
+ class CssLoadingRuntimeModule extends RuntimeModule {
27
+ /**
28
+ * @param {Compilation} compilation the compilation
29
+ * @returns {JsonpCompilationPluginHooks} hooks
30
+ */
31
+ static getCompilationHooks(compilation) {
32
+ if (!(compilation instanceof Compilation)) {
33
+ throw new TypeError(
34
+ "The 'compilation' argument must be an instance of Compilation"
35
+ );
36
+ }
37
+ let hooks = compilationHooksMap.get(compilation);
38
+ if (hooks === undefined) {
39
+ hooks = {
40
+ createStylesheet: new SyncWaterfallHook(["source", "chunk"])
41
+ };
42
+ compilationHooksMap.set(compilation, hooks);
43
+ }
44
+ return hooks;
45
+ }
46
+
47
+ constructor(runtimeRequirements, runtimeOptions) {
48
+ super("css loading", 10);
49
+
50
+ this._runtimeRequirements = runtimeRequirements;
51
+ this.runtimeOptions = runtimeOptions;
52
+ }
53
+
54
+ /**
55
+ * @returns {string} runtime code
56
+ */
57
+ generate() {
58
+ const { compilation, chunk, _runtimeRequirements } = this;
59
+ const {
60
+ chunkGraph,
61
+ runtimeTemplate,
62
+ outputOptions: {
63
+ crossOriginLoading,
64
+ uniqueName,
65
+ chunkLoadTimeout: loadTimeout
66
+ }
67
+ } = compilation;
68
+ const fn = RuntimeGlobals.ensureChunkHandlers;
69
+ const conditionMap = chunkGraph.getChunkConditionMap(
70
+ chunk,
71
+ (chunk, chunkGraph) =>
72
+ !!chunkGraph.getChunkModulesIterableBySourceType(chunk, "css")
73
+ );
74
+ const hasCssMatcher = compileBooleanMatcher(conditionMap);
75
+
76
+ const withLoading =
77
+ _runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) &&
78
+ hasCssMatcher !== false;
79
+ const withHmr = _runtimeRequirements.has(
80
+ RuntimeGlobals.hmrDownloadUpdateHandlers
81
+ );
82
+
83
+ if (!withLoading && !withHmr) {
84
+ return null;
85
+ }
86
+
87
+ const { createStylesheet } =
88
+ CssLoadingRuntimeModule.getCompilationHooks(compilation);
89
+
90
+ const initialChunkIdsWithCss = new Set();
91
+ const initialChunkIdsWithoutCss = new Set();
92
+ for (const c of chunk.getAllInitialChunks()) {
93
+ (chunkHasCss(c, chunkGraph)
94
+ ? initialChunkIdsWithCss
95
+ : initialChunkIdsWithoutCss
96
+ ).add(c.id);
97
+ }
98
+
99
+ const stateExpression = withHmr
100
+ ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css`
101
+ : undefined;
102
+
103
+ const code = Template.asString([
104
+ "link = document.createElement('link');",
105
+ uniqueName
106
+ ? 'link.setAttribute("data-webpack", uniqueName + ":" + key);'
107
+ : "",
108
+ "link.setAttribute(loadingAttribute, 1);",
109
+ 'link.rel = "stylesheet";',
110
+ withHmr ? 'if(hmr) link.media = "print and screen";' : "",
111
+ "link.href = url;",
112
+ crossOriginLoading
113
+ ? Template.asString([
114
+ "if (link.src.indexOf(window.location.origin + '/') !== 0) {",
115
+ Template.indent(
116
+ `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
117
+ ),
118
+ "}"
119
+ ])
120
+ : ""
121
+ ]);
122
+
123
+ const cc = str => str.charCodeAt(0);
124
+
125
+ return Template.asString([
126
+ "// object to store loaded and loading chunks",
127
+ "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
128
+ "// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
129
+ `var installedChunks = ${
130
+ stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
131
+ }{${Array.from(
132
+ initialChunkIdsWithoutCss,
133
+ id => `${JSON.stringify(id)}:0`
134
+ ).join(",")}};`,
135
+ "",
136
+ uniqueName
137
+ ? `var uniqueName = ${JSON.stringify(
138
+ runtimeTemplate.outputOptions.uniqueName
139
+ )};`
140
+ : "// data-webpack is not used as build has no uniqueName",
141
+ `var loadCssChunkData = ${runtimeTemplate.basicFunction("chunkId, link", [
142
+ 'var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], i = 0, cc = 1;',
143
+ "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }",
144
+ `data = data.getPropertyValue(${
145
+ uniqueName
146
+ ? runtimeTemplate.concatenation(
147
+ "--webpack-",
148
+ { expr: "uniqueName" },
149
+ "-",
150
+ { expr: "chunkId" }
151
+ )
152
+ : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" })
153
+ });`,
154
+ "if(!data) return;",
155
+ "for(; cc; i++) {",
156
+ Template.indent([
157
+ "cc = data.charCodeAt(i);",
158
+ `if(cc == ${cc("(")}) { token2 = token; token = ""; }`,
159
+ `else if(cc == ${cc(
160
+ ")"
161
+ )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`,
162
+ `else if(cc == ${cc("/")} || cc == ${cc(
163
+ "%"
164
+ )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc(
165
+ "%"
166
+ )}) exportsWithDashes.push(token); token = ""; }`,
167
+ `else if(!cc || cc == ${cc(
168
+ ","
169
+ )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction(
170
+ `exports[x] = ${
171
+ uniqueName
172
+ ? runtimeTemplate.concatenation(
173
+ { expr: "uniqueName" },
174
+ "-",
175
+ { expr: "token" },
176
+ "-",
177
+ { expr: "exports[x]" }
178
+ )
179
+ : runtimeTemplate.concatenation({ expr: "token" }, "-", {
180
+ expr: "exports[x]"
181
+ })
182
+ }`,
183
+ "x"
184
+ )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction(
185
+ `exports[x] = "--" + exports[x]`,
186
+ "x"
187
+ )}); ${RuntimeGlobals.makeNamespaceObject}(exports); ${
188
+ RuntimeGlobals.moduleFactories
189
+ }[token] = (${runtimeTemplate.basicFunction(
190
+ "exports, module",
191
+ `module.exports = exports;`
192
+ )}).bind(null, exports); token = ""; exports = {}; exportsWithId.length = 0; }`,
193
+ `else if(cc == ${cc("\\")}) { token += data[++i] }`,
194
+ `else { token += data[i]; }`
195
+ ]),
196
+ "}",
197
+ "installedChunks[chunkId] = 0;"
198
+ ])}`,
199
+ 'var loadingAttribute = "data-webpack-loading";',
200
+ `var loadStylesheet = ${runtimeTemplate.basicFunction(
201
+ "chunkId, url, done" + (withHmr ? ", hmr" : ""),
202
+ [
203
+ 'var link, needAttach, key = "chunk-" + chunkId;',
204
+ withHmr ? "if(!hmr) {" : "",
205
+ 'var links = document.getElementsByTagName("link");',
206
+ "for(var i = 0; i < links.length; i++) {",
207
+ Template.indent([
208
+ "var l = links[i];",
209
+ `if(l.getAttribute("href") == url${
210
+ uniqueName
211
+ ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key'
212
+ : ""
213
+ }) { link = l; break; }`
214
+ ]),
215
+ "}",
216
+ "if(!url) return link;",
217
+ withHmr ? "}" : "",
218
+ "if(!link) {",
219
+ Template.indent([
220
+ "needAttach = true;",
221
+ createStylesheet.call(code, this.chunk)
222
+ ]),
223
+ "}",
224
+ `var onLinkComplete = ${runtimeTemplate.basicFunction(
225
+ "prev, event",
226
+ Template.asString([
227
+ "link.onerror = link.onload = null;",
228
+ "link.removeAttribute(loadingAttribute);",
229
+ "clearTimeout(timeout);",
230
+ 'if(event && event.type != "load") link.parentNode.removeChild(link)',
231
+ "done(event);",
232
+ "if(prev) return prev(event);"
233
+ ])
234
+ )};`,
235
+ "if(link.getAttribute(loadingAttribute)) {",
236
+ Template.indent([
237
+ `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`,
238
+ "link.onerror = onLinkComplete.bind(null, link.onerror);",
239
+ "link.onload = onLinkComplete.bind(null, link.onload);"
240
+ ]),
241
+ "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking
242
+ "needAttach && document.head.appendChild(link);",
243
+ "return link;"
244
+ ]
245
+ )};`,
246
+ initialChunkIdsWithCss.size > 5
247
+ ? `${JSON.stringify(
248
+ Array.from(initialChunkIdsWithCss)
249
+ )}.forEach(loadCssChunkData);`
250
+ : initialChunkIdsWithCss.size > 0
251
+ ? `${Array.from(
252
+ initialChunkIdsWithCss,
253
+ id => `loadCssChunkData(${JSON.stringify(id)});`
254
+ ).join("")}`
255
+ : "// no initial css",
256
+ "",
257
+ withLoading
258
+ ? Template.asString([
259
+ `${fn}.css = ${runtimeTemplate.basicFunction(
260
+ "chunkId, promises",
261
+ hasCssMatcher !== false
262
+ ? [
263
+ "// css chunk loading",
264
+ `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
265
+ 'if(installedChunkData !== 0) { // 0 means "already installed".',
266
+ Template.indent([
267
+ "",
268
+ '// a Promise means "currently loading".',
269
+ "if(installedChunkData) {",
270
+ Template.indent([
271
+ "promises.push(installedChunkData[2]);"
272
+ ]),
273
+ "} else {",
274
+ Template.indent([
275
+ hasCssMatcher === true
276
+ ? "if(true) { // all chunks have CSS"
277
+ : `if(${hasCssMatcher("chunkId")}) {`,
278
+ Template.indent([
279
+ "// setup Promise in chunk cache",
280
+ `var promise = new Promise(${runtimeTemplate.expressionFunction(
281
+ `installedChunkData = installedChunks[chunkId] = [resolve, reject]`,
282
+ "resolve, reject"
283
+ )});`,
284
+ "promises.push(installedChunkData[2] = promise);",
285
+ "",
286
+ "// start chunk loading",
287
+ `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
288
+ "// create error before stack unwound to get useful stacktrace later",
289
+ "var error = new Error();",
290
+ `var loadingEnded = ${runtimeTemplate.basicFunction(
291
+ "event",
292
+ [
293
+ `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`,
294
+ Template.indent([
295
+ "installedChunkData = installedChunks[chunkId];",
296
+ "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;",
297
+ "if(installedChunkData) {",
298
+ Template.indent([
299
+ 'if(event.type !== "load") {',
300
+ Template.indent([
301
+ "var errorType = event && event.type;",
302
+ "var realSrc = event && event.target && event.target.src;",
303
+ "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
304
+ "error.name = 'ChunkLoadError';",
305
+ "error.type = errorType;",
306
+ "error.request = realSrc;",
307
+ "installedChunkData[1](error);"
308
+ ]),
309
+ "} else {",
310
+ Template.indent([
311
+ "loadCssChunkData(chunkId, link);",
312
+ "installedChunkData[0]();"
313
+ ]),
314
+ "}"
315
+ ]),
316
+ "}"
317
+ ]),
318
+ "}"
319
+ ]
320
+ )};`,
321
+ "var link = loadStylesheet(chunkId, url, loadingEnded);"
322
+ ]),
323
+ "} else installedChunks[chunkId] = 0;"
324
+ ]),
325
+ "}"
326
+ ]),
327
+ "}"
328
+ ]
329
+ : "installedChunks[chunkId] = 0;"
330
+ )};`
331
+ ])
332
+ : "// no chunk loading",
333
+ "",
334
+ withHmr
335
+ ? Template.asString([
336
+ "var oldTags = [];",
337
+ "var newTags = [];",
338
+ `var applyHandler = ${runtimeTemplate.basicFunction("options", [
339
+ `return { dispose: ${runtimeTemplate.basicFunction("", [
340
+ "while(oldTags.length) {",
341
+ Template.indent([
342
+ "var oldTag = oldTags.pop();",
343
+ "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
344
+ ]),
345
+ "}"
346
+ ])}, apply: ${runtimeTemplate.basicFunction("", [
347
+ 'while(newTags.length) { var info = newTags.pop(); info[1].media = "all"; loadCssChunkData(info[0], info[1]); }'
348
+ ])} };`
349
+ ])}`,
350
+ `${
351
+ RuntimeGlobals.hmrDownloadUpdateHandlers
352
+ }.css = ${runtimeTemplate.basicFunction(
353
+ "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList",
354
+ [
355
+ "applyHandlers.push(applyHandler);",
356
+ `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
357
+ "var oldTag = loadStylesheet(chunkId);",
358
+ "if(!oldTag) return;",
359
+ `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
360
+ `var url = ${RuntimeGlobals.publicPath} + filename;`,
361
+ `promises.push(new Promise(${runtimeTemplate.basicFunction(
362
+ "resolve, reject",
363
+ [
364
+ `var link = loadStylesheet(chunkId, url, ${runtimeTemplate.basicFunction(
365
+ "event",
366
+ [
367
+ 'if(event.type !== "load") {',
368
+ Template.indent([
369
+ "var errorType = event && event.type;",
370
+ "var realSrc = event && event.target && event.target.src;",
371
+ "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
372
+ "error.name = 'ChunkLoadError';",
373
+ "error.type = errorType;",
374
+ "error.request = realSrc;",
375
+ "reject(error);"
376
+ ]),
377
+ "} else resolve();"
378
+ ]
379
+ )}, true);`,
380
+ "oldTags.push(oldTag);",
381
+ "newTags.push([chunkId, link]);"
382
+ ]
383
+ )}));`
384
+ ])});`
385
+ ]
386
+ )}`
387
+ ])
388
+ : "// no hmr"
389
+ ]);
390
+ }
391
+ }
392
+
393
+ module.exports = CssLoadingRuntimeModule;