webpack 5.66.0 → 5.69.1

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 (97) hide show
  1. package/README.md +1 -1
  2. package/lib/APIPlugin.js +33 -0
  3. package/lib/Cache.js +1 -1
  4. package/lib/CacheFacade.js +2 -2
  5. package/lib/ChunkGraph.js +1 -2
  6. package/lib/CleanPlugin.js +1 -1
  7. package/lib/Compilation.js +14 -9
  8. package/lib/Compiler.js +57 -3
  9. package/lib/ContextModule.js +21 -17
  10. package/lib/DelegatedModule.js +1 -1
  11. package/lib/DependencyTemplates.js +1 -1
  12. package/lib/DllModule.js +1 -1
  13. package/lib/EvalDevToolModulePlugin.js +16 -1
  14. package/lib/EvalSourceMapDevToolPlugin.js +18 -1
  15. package/lib/ExportsInfo.js +4 -4
  16. package/lib/ExternalModule.js +1 -1
  17. package/lib/ExternalModuleFactoryPlugin.js +1 -1
  18. package/lib/FileSystemInfo.js +29 -25
  19. package/lib/HookWebpackError.js +1 -1
  20. package/lib/Module.js +1 -3
  21. package/lib/MultiCompiler.js +1 -1
  22. package/lib/MultiWatching.js +1 -1
  23. package/lib/NormalModule.js +6 -4
  24. package/lib/NormalModuleFactory.js +25 -27
  25. package/lib/ProgressPlugin.js +1 -1
  26. package/lib/RawModule.js +1 -1
  27. package/lib/RuntimeGlobals.js +18 -0
  28. package/lib/RuntimeModule.js +1 -1
  29. package/lib/RuntimePlugin.js +28 -3
  30. package/lib/RuntimeTemplate.js +1 -1
  31. package/lib/TemplatedPathPlugin.js +48 -23
  32. package/lib/Watching.js +1 -1
  33. package/lib/WebpackOptionsApply.js +1 -1
  34. package/lib/asset/AssetGenerator.js +65 -26
  35. package/lib/asset/AssetModulesPlugin.js +3 -0
  36. package/lib/asset/RawDataUrlModule.js +8 -5
  37. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -4
  38. package/lib/buildChunkGraph.js +1 -1
  39. package/lib/cache/ResolverCachePlugin.js +1 -1
  40. package/lib/cli.js +44 -3
  41. package/lib/config/defaults.js +30 -7
  42. package/lib/config/normalization.js +5 -0
  43. package/lib/container/ContainerEntryModule.js +4 -2
  44. package/lib/container/FallbackModule.js +4 -4
  45. package/lib/container/RemoteModule.js +4 -2
  46. package/lib/css/CssExportsGenerator.js +139 -0
  47. package/lib/css/CssGenerator.js +3 -0
  48. package/lib/css/CssLoadingRuntimeModule.js +201 -154
  49. package/lib/css/CssModulesPlugin.js +22 -4
  50. package/lib/debug/ProfilingPlugin.js +15 -14
  51. package/lib/dependencies/ContextElementDependency.js +8 -2
  52. package/lib/dependencies/CreateScriptUrlDependency.js +12 -0
  53. package/lib/dependencies/ExportsInfoDependency.js +6 -0
  54. package/lib/dependencies/HarmonyCompatibilityDependency.js +5 -5
  55. package/lib/dependencies/ImportMetaPlugin.js +22 -3
  56. package/lib/dependencies/LoaderPlugin.js +2 -2
  57. package/lib/hmr/LazyCompilationPlugin.js +45 -21
  58. package/lib/hmr/lazyCompilationBackend.js +1 -1
  59. package/lib/ids/DeterministicModuleIdsPlugin.js +55 -35
  60. package/lib/ids/HashedModuleIdsPlugin.js +9 -12
  61. package/lib/ids/IdHelpers.js +24 -10
  62. package/lib/ids/NamedModuleIdsPlugin.js +6 -9
  63. package/lib/ids/NaturalModuleIdsPlugin.js +10 -13
  64. package/lib/ids/OccurrenceModuleIdsPlugin.js +13 -10
  65. package/lib/ids/SyncModuleIdsPlugin.js +140 -0
  66. package/lib/index.js +10 -0
  67. package/lib/javascript/JavascriptModulesPlugin.js +27 -2
  68. package/lib/javascript/StartupHelpers.js +3 -2
  69. package/lib/library/AssignLibraryPlugin.js +8 -2
  70. package/lib/node/NodeTargetPlugin.js +1 -0
  71. package/lib/optimize/ConcatenatedModule.js +11 -5
  72. package/lib/runtime/AsyncModuleRuntimeModule.js +25 -15
  73. package/lib/runtime/CreateScriptRuntimeModule.js +36 -0
  74. package/lib/runtime/CreateScriptUrlRuntimeModule.js +9 -34
  75. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +76 -0
  76. package/lib/schemes/HttpUriPlugin.js +32 -11
  77. package/lib/serialization/FileMiddleware.js +44 -9
  78. package/lib/sharing/ConsumeSharedModule.js +4 -2
  79. package/lib/sharing/ProvideSharedModule.js +4 -2
  80. package/lib/sharing/utils.js +1 -1
  81. package/lib/stats/DefaultStatsFactoryPlugin.js +112 -67
  82. package/lib/stats/DefaultStatsPrinterPlugin.js +88 -23
  83. package/lib/util/ArrayHelpers.js +18 -4
  84. package/lib/util/AsyncQueue.js +1 -1
  85. package/lib/util/compileBooleanMatcher.js +1 -1
  86. package/lib/util/deterministicGrouping.js +1 -1
  87. package/lib/util/identifier.js +65 -44
  88. package/lib/util/nonNumericOnlyHash.js +22 -0
  89. package/lib/util/semver.js +17 -10
  90. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +9 -3
  91. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -11
  92. package/package.json +14 -21
  93. package/schemas/WebpackOptions.check.js +1 -1
  94. package/schemas/WebpackOptions.json +47 -6
  95. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  96. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  97. package/types.d.ts +207 -60
@@ -0,0 +1,139 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Sergey Melyukov @smelukov
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const { ReplaceSource, RawSource, ConcatSource } = require("webpack-sources");
9
+ const { UsageState } = require("../ExportsInfo");
10
+ const Generator = require("../Generator");
11
+ const RuntimeGlobals = require("../RuntimeGlobals");
12
+ const Template = require("../Template");
13
+
14
+ /** @typedef {import("webpack-sources").Source} Source */
15
+ /** @typedef {import("../Dependency")} Dependency */
16
+ /** @typedef {import("../Generator").GenerateContext} GenerateContext */
17
+ /** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
18
+ /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
19
+ /** @typedef {import("../NormalModule")} NormalModule */
20
+ /** @typedef {import("../util/Hash")} Hash */
21
+
22
+ const TYPES = new Set(["javascript"]);
23
+
24
+ class CssExportsGenerator extends Generator {
25
+ constructor() {
26
+ super();
27
+ }
28
+
29
+ // TODO add getConcatenationBailoutReason to allow concatenation
30
+ // but how to make it have a module id
31
+
32
+ /**
33
+ * @param {NormalModule} module module for which the code should be generated
34
+ * @param {GenerateContext} generateContext context for generate
35
+ * @returns {Source} generated code
36
+ */
37
+ generate(module, generateContext) {
38
+ const source = new ReplaceSource(new RawSource(""));
39
+ const initFragments = [];
40
+ const cssExports = new Map();
41
+
42
+ generateContext.runtimeRequirements.add(RuntimeGlobals.module);
43
+
44
+ const runtimeRequirements = new Set();
45
+
46
+ const templateContext = {
47
+ runtimeTemplate: generateContext.runtimeTemplate,
48
+ dependencyTemplates: generateContext.dependencyTemplates,
49
+ moduleGraph: generateContext.moduleGraph,
50
+ chunkGraph: generateContext.chunkGraph,
51
+ module,
52
+ runtime: generateContext.runtime,
53
+ runtimeRequirements: runtimeRequirements,
54
+ concatenationScope: generateContext.concatenationScope,
55
+ codeGenerationResults: generateContext.codeGenerationResults,
56
+ initFragments,
57
+ cssExports
58
+ };
59
+
60
+ const handleDependency = dependency => {
61
+ const constructor = /** @type {new (...args: any[]) => Dependency} */ (
62
+ dependency.constructor
63
+ );
64
+ const template = generateContext.dependencyTemplates.get(constructor);
65
+ if (!template) {
66
+ throw new Error(
67
+ "No template for dependency: " + dependency.constructor.name
68
+ );
69
+ }
70
+
71
+ template.apply(dependency, source, templateContext);
72
+ };
73
+ module.dependencies.forEach(handleDependency);
74
+
75
+ if (generateContext.concatenationScope) {
76
+ const source = new ConcatSource();
77
+ const usedIdentifiers = new Set();
78
+ for (const [k, v] of cssExports) {
79
+ let identifier = Template.toIdentifier(k);
80
+ let i = 0;
81
+ while (usedIdentifiers.has(identifier)) {
82
+ identifier = Template.toIdentifier(k + i);
83
+ }
84
+ usedIdentifiers.add(identifier);
85
+ generateContext.concatenationScope.registerExport(k, identifier);
86
+ source.add(
87
+ `${
88
+ generateContext.runtimeTemplate.supportsConst ? "const" : "var"
89
+ } ${identifier} = ${JSON.stringify(v)};\n`
90
+ );
91
+ }
92
+ return source;
93
+ } else {
94
+ const otherUsed =
95
+ generateContext.moduleGraph
96
+ .getExportsInfo(module)
97
+ .otherExportsInfo.getUsed(generateContext.runtime) !==
98
+ UsageState.Unused;
99
+ if (otherUsed) {
100
+ generateContext.runtimeRequirements.add(
101
+ RuntimeGlobals.makeNamespaceObject
102
+ );
103
+ }
104
+ return new RawSource(
105
+ `${otherUsed ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
106
+ module.moduleArgument
107
+ }.exports = {\n${Array.from(
108
+ cssExports,
109
+ ([k, v]) => `\t${JSON.stringify(k)}: ${JSON.stringify(v)}`
110
+ ).join(",\n")}\n}${otherUsed ? ")" : ""};`
111
+ );
112
+ }
113
+ }
114
+
115
+ /**
116
+ * @param {NormalModule} module fresh module
117
+ * @returns {Set<string>} available types (do not mutate)
118
+ */
119
+ getTypes(module) {
120
+ return TYPES;
121
+ }
122
+
123
+ /**
124
+ * @param {NormalModule} module the module
125
+ * @param {string=} type source type
126
+ * @returns {number} estimate size of the module
127
+ */
128
+ getSize(module, type) {
129
+ return 42;
130
+ }
131
+
132
+ /**
133
+ * @param {Hash} hash hash that will be modified
134
+ * @param {UpdateHashContext} updateHashContext context for updating hash
135
+ */
136
+ updateHash(hash, { module }) {}
137
+ }
138
+
139
+ module.exports = CssExportsGenerator;
@@ -8,6 +8,7 @@
8
8
  const { ReplaceSource } = require("webpack-sources");
9
9
  const Generator = require("../Generator");
10
10
  const InitFragment = require("../InitFragment");
11
+ const RuntimeGlobals = require("../RuntimeGlobals");
11
12
 
12
13
  /** @typedef {import("webpack-sources").Source} Source */
13
14
  /** @typedef {import("../Dependency")} Dependency */
@@ -34,6 +35,8 @@ class CssGenerator extends Generator {
34
35
  const initFragments = [];
35
36
  const cssExports = new Map();
36
37
 
38
+ generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
39
+
37
40
  const templateContext = {
38
41
  runtimeTemplate: generateContext.runtimeTemplate,
39
42
  dependencyTemplates: generateContext.dependencyTemplates,
@@ -79,14 +79,6 @@ class CssLoadingRuntimeModule extends RuntimeModule {
79
79
  const withHmr = _runtimeRequirements.has(
80
80
  RuntimeGlobals.hmrDownloadUpdateHandlers
81
81
  );
82
-
83
- if (!withLoading && !withHmr) {
84
- return null;
85
- }
86
-
87
- const { createStylesheet } =
88
- CssLoadingRuntimeModule.getCompilationHooks(compilation);
89
-
90
82
  const initialChunkIdsWithCss = new Set();
91
83
  const initialChunkIdsWithoutCss = new Set();
92
84
  for (const c of chunk.getAllInitialChunks()) {
@@ -96,6 +88,13 @@ class CssLoadingRuntimeModule extends RuntimeModule {
96
88
  ).add(c.id);
97
89
  }
98
90
 
91
+ if (!withLoading && !withHmr && initialChunkIdsWithCss.size === 0) {
92
+ return null;
93
+ }
94
+
95
+ const { createStylesheet } =
96
+ CssLoadingRuntimeModule.getCompilationHooks(compilation);
97
+
99
98
  const stateExpression = withHmr
100
99
  ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css`
101
100
  : undefined;
@@ -107,7 +106,6 @@ class CssLoadingRuntimeModule extends RuntimeModule {
107
106
  : "",
108
107
  "link.setAttribute(loadingAttribute, 1);",
109
108
  'link.rel = "stylesheet";',
110
- withHmr ? 'if(hmr) link.media = "print and screen";' : "",
111
109
  "link.href = url;",
112
110
  crossOriginLoading
113
111
  ? Template.asString([
@@ -138,64 +136,74 @@ class CssLoadingRuntimeModule extends RuntimeModule {
138
136
  runtimeTemplate.outputOptions.uniqueName
139
137
  )};`
140
138
  : "// 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
- ])}`,
139
+ `var loadCssChunkData = ${runtimeTemplate.basicFunction(
140
+ "target, link, chunkId",
141
+ [
142
+ `var data, token = "", token2, exports = {}, exportsWithId = [], exportsWithDashes = [], ${
143
+ withHmr ? "moduleIds = [], " : ""
144
+ }i = 0, cc = 1;`,
145
+ "try { if(!link) link = loadStylesheet(chunkId); data = link.sheet.cssRules; data = data[data.length - 1].style; } catch(e) { data = getComputedStyle(document.head); }",
146
+ `data = data.getPropertyValue(${
147
+ uniqueName
148
+ ? runtimeTemplate.concatenation(
149
+ "--webpack-",
150
+ { expr: "uniqueName" },
151
+ "-",
152
+ { expr: "chunkId" }
153
+ )
154
+ : runtimeTemplate.concatenation("--webpack-", { expr: "chunkId" })
155
+ });`,
156
+ "if(!data) return [];",
157
+ "for(; cc; i++) {",
158
+ Template.indent([
159
+ "cc = data.charCodeAt(i);",
160
+ `if(cc == ${cc("(")}) { token2 = token; token = ""; }`,
161
+ `else if(cc == ${cc(
162
+ ")"
163
+ )}) { exports[token2.replace(/^_/, "")] = token.replace(/^_/, ""); token = ""; }`,
164
+ `else if(cc == ${cc("/")} || cc == ${cc(
165
+ "%"
166
+ )}) { token = token.replace(/^_/, ""); exports[token] = token; exportsWithId.push(token); if(cc == ${cc(
167
+ "%"
168
+ )}) exportsWithDashes.push(token); token = ""; }`,
169
+ `else if(!cc || cc == ${cc(
170
+ ","
171
+ )}) { token = token.replace(/^_/, ""); exportsWithId.forEach(${runtimeTemplate.expressionFunction(
172
+ `exports[x] = ${
173
+ uniqueName
174
+ ? runtimeTemplate.concatenation(
175
+ { expr: "uniqueName" },
176
+ "-",
177
+ { expr: "token" },
178
+ "-",
179
+ { expr: "exports[x]" }
180
+ )
181
+ : runtimeTemplate.concatenation({ expr: "token" }, "-", {
182
+ expr: "exports[x]"
183
+ })
184
+ }`,
185
+ "x"
186
+ )}); exportsWithDashes.forEach(${runtimeTemplate.expressionFunction(
187
+ `exports[x] = "--" + exports[x]`,
188
+ "x"
189
+ )}); ${
190
+ RuntimeGlobals.makeNamespaceObject
191
+ }(exports); target[token] = (${runtimeTemplate.basicFunction(
192
+ "exports, module",
193
+ `module.exports = exports;`
194
+ )}).bind(null, exports); ${
195
+ withHmr ? "moduleIds.push(token); " : ""
196
+ }token = ""; exports = {}; exportsWithId.length = 0; }`,
197
+ `else if(cc == ${cc("\\")}) { token += data[++i] }`,
198
+ `else { token += data[i]; }`
199
+ ]),
200
+ "}",
201
+ `${
202
+ withHmr ? `if(target == ${RuntimeGlobals.moduleFactories}) ` : ""
203
+ }installedChunks[chunkId] = 0;`,
204
+ withHmr ? "return moduleIds;" : ""
205
+ ]
206
+ )}`,
199
207
  'var loadingAttribute = "data-webpack-loading";',
200
208
  `var loadStylesheet = ${runtimeTemplate.basicFunction(
201
209
  "chunkId, url, done" + (withHmr ? ", hmr" : ""),
@@ -206,14 +214,18 @@ class CssLoadingRuntimeModule extends RuntimeModule {
206
214
  "for(var i = 0; i < links.length; i++) {",
207
215
  Template.indent([
208
216
  "var l = links[i];",
209
- `if(l.getAttribute("href") == url${
217
+ `if(l.rel == "stylesheet" && (${
218
+ withHmr
219
+ ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)'
220
+ : 'l.href == url || l.getAttribute("href") == url'
221
+ }${
210
222
  uniqueName
211
223
  ? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key'
212
224
  : ""
213
- }) { link = l; break; }`
225
+ })) { link = l; break; }`
214
226
  ]),
215
227
  "}",
216
- "if(!url) return link;",
228
+ "if(!done) return link;",
217
229
  withHmr ? "}" : "",
218
230
  "if(!link) {",
219
231
  Template.indent([
@@ -239,95 +251,94 @@ class CssLoadingRuntimeModule extends RuntimeModule {
239
251
  "link.onload = onLinkComplete.bind(null, link.onload);"
240
252
  ]),
241
253
  "} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking
254
+ withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "",
242
255
  "needAttach && document.head.appendChild(link);",
243
256
  "return link;"
244
257
  ]
245
258
  )};`,
246
- initialChunkIdsWithCss.size > 5
259
+ initialChunkIdsWithCss.size > 2
247
260
  ? `${JSON.stringify(
248
261
  Array.from(initialChunkIdsWithCss)
249
- )}.forEach(loadCssChunkData);`
262
+ )}.forEach(loadCssChunkData.bind(null, ${
263
+ RuntimeGlobals.moduleFactories
264
+ }, 0));`
250
265
  : initialChunkIdsWithCss.size > 0
251
266
  ? `${Array.from(
252
267
  initialChunkIdsWithCss,
253
- id => `loadCssChunkData(${JSON.stringify(id)});`
268
+ id =>
269
+ `loadCssChunkData(${
270
+ RuntimeGlobals.moduleFactories
271
+ }, 0, ${JSON.stringify(id)});`
254
272
  ).join("")}`
255
273
  : "// no initial css",
256
274
  "",
257
275
  withLoading
258
276
  ? 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")}) {`,
277
+ `${fn}.css = ${runtimeTemplate.basicFunction("chunkId, promises", [
278
+ "// css chunk loading",
279
+ `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
280
+ 'if(installedChunkData !== 0) { // 0 means "already installed".',
281
+ Template.indent([
282
+ "",
283
+ '// a Promise means "currently loading".',
284
+ "if(installedChunkData) {",
285
+ Template.indent(["promises.push(installedChunkData[2]);"]),
286
+ "} else {",
287
+ Template.indent([
288
+ hasCssMatcher === true
289
+ ? "if(true) { // all chunks have CSS"
290
+ : `if(${hasCssMatcher("chunkId")}) {`,
291
+ Template.indent([
292
+ "// setup Promise in chunk cache",
293
+ `var promise = new Promise(${runtimeTemplate.expressionFunction(
294
+ `installedChunkData = installedChunks[chunkId] = [resolve, reject]`,
295
+ "resolve, reject"
296
+ )});`,
297
+ "promises.push(installedChunkData[2] = promise);",
298
+ "",
299
+ "// start chunk loading",
300
+ `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
301
+ "// create error before stack unwound to get useful stacktrace later",
302
+ "var error = new Error();",
303
+ `var loadingEnded = ${runtimeTemplate.basicFunction(
304
+ "event",
305
+ [
306
+ `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`,
278
307
  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);"
308
+ "installedChunkData = installedChunks[chunkId];",
309
+ "if(installedChunkData !== 0) installedChunks[chunkId] = undefined;",
310
+ "if(installedChunkData) {",
311
+ Template.indent([
312
+ 'if(event.type !== "load") {',
313
+ Template.indent([
314
+ "var errorType = event && event.type;",
315
+ "var realSrc = event && event.target && event.target.src;",
316
+ "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
317
+ "error.name = 'ChunkLoadError';",
318
+ "error.type = errorType;",
319
+ "error.request = realSrc;",
320
+ "installedChunkData[1](error);"
321
+ ]),
322
+ "} else {",
323
+ Template.indent([
324
+ `loadCssChunkData(${RuntimeGlobals.moduleFactories}, link, chunkId);`,
325
+ "installedChunkData[0]();"
326
+ ]),
327
+ "}"
328
+ ]),
329
+ "}"
322
330
  ]),
323
- "} else installedChunks[chunkId] = 0;"
324
- ]),
325
- "}"
326
- ]),
327
- "}"
328
- ]
329
- : "installedChunks[chunkId] = 0;"
330
- )};`
331
+ "}"
332
+ ]
333
+ )};`,
334
+ "var link = loadStylesheet(chunkId, url, loadingEnded);"
335
+ ]),
336
+ "} else installedChunks[chunkId] = 0;"
337
+ ]),
338
+ "}"
339
+ ]),
340
+ "}"
341
+ ])};`
331
342
  ])
332
343
  : "// no chunk loading",
333
344
  "",
@@ -336,17 +347,41 @@ class CssLoadingRuntimeModule extends RuntimeModule {
336
347
  "var oldTags = [];",
337
348
  "var newTags = [];",
338
349
  `var applyHandler = ${runtimeTemplate.basicFunction("options", [
339
- `return { dispose: ${runtimeTemplate.basicFunction("", [
350
+ `return { dispose: ${runtimeTemplate.basicFunction(
351
+ "",
352
+ []
353
+ )}, apply: ${runtimeTemplate.basicFunction("", [
354
+ "var moduleIds = [];",
355
+ `newTags.forEach(${runtimeTemplate.expressionFunction(
356
+ "info[1].sheet.disabled = false",
357
+ "info"
358
+ )});`,
340
359
  "while(oldTags.length) {",
341
360
  Template.indent([
342
361
  "var oldTag = oldTags.pop();",
343
362
  "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
344
363
  ]),
345
- "}"
346
- ])}, apply: ${runtimeTemplate.basicFunction("", [
347
- 'while(newTags.length) { var info = newTags.pop(); info[1].media = "all"; loadCssChunkData(info[0], info[1]); }'
364
+ "}",
365
+ "while(newTags.length) {",
366
+ Template.indent([
367
+ `var info = newTags.pop();`,
368
+ `var chunkModuleIds = loadCssChunkData(${RuntimeGlobals.moduleFactories}, info[1], info[0]);`,
369
+ `chunkModuleIds.forEach(${runtimeTemplate.expressionFunction(
370
+ "moduleIds.push(id)",
371
+ "id"
372
+ )});`
373
+ ]),
374
+ "}",
375
+ "return moduleIds;"
348
376
  ])} };`
349
377
  ])}`,
378
+ `var cssTextKey = ${runtimeTemplate.returningFunction(
379
+ `Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction(
380
+ "r.cssText",
381
+ "r"
382
+ )}).join()`,
383
+ "link"
384
+ )}`,
350
385
  `${
351
386
  RuntimeGlobals.hmrDownloadUpdateHandlers
352
387
  }.css = ${runtimeTemplate.basicFunction(
@@ -354,14 +389,14 @@ class CssLoadingRuntimeModule extends RuntimeModule {
354
389
  [
355
390
  "applyHandlers.push(applyHandler);",
356
391
  `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
357
- "var oldTag = loadStylesheet(chunkId);",
358
- "if(!oldTag) return;",
359
392
  `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
360
393
  `var url = ${RuntimeGlobals.publicPath} + filename;`,
394
+ "var oldTag = loadStylesheet(chunkId, url);",
395
+ "if(!oldTag) return;",
361
396
  `promises.push(new Promise(${runtimeTemplate.basicFunction(
362
397
  "resolve, reject",
363
398
  [
364
- `var link = loadStylesheet(chunkId, url, ${runtimeTemplate.basicFunction(
399
+ `var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction(
365
400
  "event",
366
401
  [
367
402
  'if(event.type !== "load") {',
@@ -374,11 +409,23 @@ class CssLoadingRuntimeModule extends RuntimeModule {
374
409
  "error.request = realSrc;",
375
410
  "reject(error);"
376
411
  ]),
377
- "} else resolve();"
412
+ "} else {",
413
+ Template.indent([
414
+ "try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}",
415
+ "var factories = {};",
416
+ "loadCssChunkData(factories, link, chunkId);",
417
+ `Object.keys(factories).forEach(${runtimeTemplate.expressionFunction(
418
+ "updatedModulesList.push(id)",
419
+ "id"
420
+ )})`,
421
+ "link.sheet.disabled = true;",
422
+ "oldTags.push(oldTag);",
423
+ "newTags.push([chunkId, link]);",
424
+ "resolve();"
425
+ ]),
426
+ "}"
378
427
  ]
379
- )}, true);`,
380
- "oldTags.push(oldTag);",
381
- "newTags.push([chunkId, link]);"
428
+ )}, oldTag);`
382
429
  ]
383
430
  )}));`
384
431
  ])});`