webpack 5.103.0 → 5.104.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.
Files changed (176) hide show
  1. package/hot/dev-server.js +18 -3
  2. package/hot/emitter-event-target.js +7 -0
  3. package/hot/lazy-compilation-node.js +45 -29
  4. package/hot/lazy-compilation-universal.js +18 -0
  5. package/hot/lazy-compilation-web.js +15 -5
  6. package/hot/load-http.js +7 -0
  7. package/hot/only-dev-server.js +19 -4
  8. package/lib/APIPlugin.js +6 -0
  9. package/lib/Chunk.js +1 -1
  10. package/lib/ChunkGraph.js +9 -7
  11. package/lib/ChunkGroup.js +8 -5
  12. package/lib/CleanPlugin.js +6 -3
  13. package/lib/CodeGenerationResults.js +2 -1
  14. package/lib/CompatibilityPlugin.js +3 -0
  15. package/lib/Compilation.js +33 -19
  16. package/lib/Compiler.js +3 -3
  17. package/lib/ContextModule.js +6 -3
  18. package/lib/ContextModuleFactory.js +6 -4
  19. package/lib/DefinePlugin.js +34 -3
  20. package/lib/DelegatedModule.js +7 -4
  21. package/lib/DllModule.js +6 -3
  22. package/lib/DotenvPlugin.js +11 -6
  23. package/lib/ExportsInfo.js +5 -5
  24. package/lib/ExternalModule.js +8 -7
  25. package/lib/ExternalModuleFactoryPlugin.js +1 -1
  26. package/lib/FileSystemInfo.js +1 -1
  27. package/lib/Generator.js +10 -7
  28. package/lib/HookWebpackError.js +33 -4
  29. package/lib/HotModuleReplacementPlugin.js +22 -0
  30. package/lib/ManifestPlugin.js +1 -1
  31. package/lib/Module.js +24 -15
  32. package/lib/ModuleBuildError.js +1 -1
  33. package/lib/ModuleError.js +1 -1
  34. package/lib/ModuleFilenameHelpers.js +1 -1
  35. package/lib/ModuleGraph.js +27 -12
  36. package/lib/ModuleGraphConnection.js +2 -2
  37. package/lib/ModuleSourceTypeConstants.js +189 -0
  38. package/lib/ModuleTypeConstants.js +1 -4
  39. package/lib/ModuleWarning.js +1 -1
  40. package/lib/NodeStuffPlugin.js +52 -42
  41. package/lib/NormalModule.js +6 -4
  42. package/lib/NormalModuleFactory.js +7 -10
  43. package/lib/Parser.js +1 -1
  44. package/lib/RawModule.js +7 -4
  45. package/lib/RuntimeModule.js +1 -1
  46. package/lib/RuntimeTemplate.js +5 -1
  47. package/lib/SourceMapDevToolPlugin.js +6 -1
  48. package/lib/Template.js +17 -6
  49. package/lib/TemplatedPathPlugin.js +5 -6
  50. package/lib/WebpackError.js +0 -1
  51. package/lib/WebpackOptionsApply.js +37 -9
  52. package/lib/asset/AssetBytesGenerator.js +15 -11
  53. package/lib/asset/AssetGenerator.js +30 -24
  54. package/lib/asset/AssetSourceGenerator.js +15 -11
  55. package/lib/asset/RawDataUrlModule.js +6 -3
  56. package/lib/buildChunkGraph.js +4 -2
  57. package/lib/cache/PackFileCacheStrategy.js +6 -5
  58. package/lib/cli.js +2 -43
  59. package/lib/config/browserslistTargetHandler.js +19 -0
  60. package/lib/config/defaults.js +128 -43
  61. package/lib/config/normalization.js +2 -2
  62. package/lib/config/target.js +5 -0
  63. package/lib/container/ContainerEntryModule.js +6 -3
  64. package/lib/container/FallbackModule.js +6 -3
  65. package/lib/container/RemoteModule.js +1 -3
  66. package/lib/css/CssGenerator.js +26 -24
  67. package/lib/css/CssLoadingRuntimeModule.js +12 -4
  68. package/lib/css/CssModulesPlugin.js +29 -74
  69. package/lib/css/CssParser.js +828 -341
  70. package/lib/css/walkCssTokens.js +33 -13
  71. package/lib/dependencies/CachedConstDependency.js +24 -10
  72. package/lib/dependencies/CommonJsRequireContextDependency.js +1 -1
  73. package/lib/dependencies/ContextDependencyHelpers.js +2 -2
  74. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +3 -1
  75. package/lib/dependencies/CssIcssExportDependency.js +242 -104
  76. package/lib/dependencies/CssIcssImportDependency.js +61 -4
  77. package/lib/dependencies/CssIcssSymbolDependency.js +2 -6
  78. package/lib/dependencies/CssImportDependency.js +2 -1
  79. package/lib/dependencies/CssUrlDependency.js +3 -2
  80. package/lib/dependencies/DynamicExports.js +7 -7
  81. package/lib/dependencies/ExternalModuleDependency.js +7 -4
  82. package/lib/dependencies/ExternalModuleInitFragment.js +2 -1
  83. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +2 -1
  84. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +3 -2
  85. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +1 -1
  86. package/lib/dependencies/HarmonyExports.js +4 -4
  87. package/lib/dependencies/HarmonyImportDependency.js +8 -3
  88. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  89. package/lib/dependencies/ImportMetaPlugin.js +57 -0
  90. package/lib/dependencies/ImportParserPlugin.js +2 -2
  91. package/lib/dependencies/LocalModulesHelpers.js +3 -3
  92. package/lib/dependencies/WorkerPlugin.js +2 -2
  93. package/lib/dependencies/getFunctionExpression.js +1 -1
  94. package/lib/esm/ModuleChunkFormatPlugin.js +5 -4
  95. package/lib/hmr/HotModuleReplacement.runtime.js +2 -1
  96. package/lib/hmr/LazyCompilationPlugin.js +4 -3
  97. package/lib/ids/IdHelpers.js +16 -7
  98. package/lib/javascript/ChunkHelpers.js +1 -1
  99. package/lib/javascript/JavascriptGenerator.js +4 -3
  100. package/lib/javascript/JavascriptModulesPlugin.js +57 -24
  101. package/lib/javascript/JavascriptParser.js +19 -6
  102. package/lib/json/JsonGenerator.js +5 -4
  103. package/lib/json/JsonParser.js +2 -1
  104. package/lib/library/AbstractLibraryPlugin.js +1 -1
  105. package/lib/library/AmdLibraryPlugin.js +4 -1
  106. package/lib/library/ExportPropertyLibraryPlugin.js +4 -1
  107. package/lib/library/ModuleLibraryPlugin.js +41 -13
  108. package/lib/library/SystemLibraryPlugin.js +4 -1
  109. package/lib/library/UmdLibraryPlugin.js +1 -1
  110. package/lib/logging/Logger.js +5 -4
  111. package/lib/logging/createConsoleLogger.js +2 -2
  112. package/lib/optimize/ConcatenatedModule.js +47 -32
  113. package/lib/optimize/ModuleConcatenationPlugin.js +5 -4
  114. package/lib/optimize/SideEffectsFlagPlugin.js +3 -2
  115. package/lib/optimize/SplitChunksPlugin.js +60 -46
  116. package/lib/rules/RuleSetCompiler.js +1 -1
  117. package/lib/runtime/GetChunkFilenameRuntimeModule.js +3 -2
  118. package/lib/schemes/HttpUriPlugin.js +78 -7
  119. package/lib/serialization/AggregateErrorSerializer.js +1 -2
  120. package/lib/serialization/ObjectMiddleware.js +0 -2
  121. package/lib/serialization/SingleItemMiddleware.js +1 -1
  122. package/lib/sharing/ConsumeSharedModule.js +1 -1
  123. package/lib/sharing/ConsumeSharedPlugin.js +5 -3
  124. package/lib/sharing/ProvideSharedModule.js +1 -1
  125. package/lib/sharing/resolveMatchedConfigs.js +15 -9
  126. package/lib/sharing/utils.js +1 -1
  127. package/lib/stats/DefaultStatsFactoryPlugin.js +8 -5
  128. package/lib/stats/DefaultStatsPresetPlugin.js +1 -1
  129. package/lib/stats/DefaultStatsPrinterPlugin.js +1 -1
  130. package/lib/util/StringXor.js +1 -1
  131. package/lib/util/URLAbsoluteSpecifier.js +2 -2
  132. package/lib/util/binarySearchBounds.js +2 -2
  133. package/lib/util/comparators.js +53 -76
  134. package/lib/util/compileBooleanMatcher.js +78 -6
  135. package/lib/util/createHash.js +20 -199
  136. package/lib/util/deprecation.js +1 -1
  137. package/lib/util/deterministicGrouping.js +6 -3
  138. package/lib/util/fs.js +75 -75
  139. package/lib/util/hash/BatchedHash.js +10 -9
  140. package/lib/util/hash/BulkUpdateHash.js +138 -0
  141. package/lib/util/hash/DebugHash.js +75 -0
  142. package/lib/util/hash/hash-digest.js +216 -0
  143. package/lib/util/identifier.js +82 -17
  144. package/lib/util/internalSerializables.js +2 -6
  145. package/lib/util/runtime.js +3 -3
  146. package/lib/util/source.js +2 -2
  147. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +3 -2
  148. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +3 -2
  149. package/lib/wasm-sync/WebAssemblyGenerator.js +9 -6
  150. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +3 -2
  151. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +6 -2
  152. package/lib/webpack.js +1 -1
  153. package/package.json +29 -25
  154. package/schemas/WebpackOptions.check.js +1 -1
  155. package/schemas/WebpackOptions.json +59 -82
  156. package/schemas/plugins/css/CssModuleGeneratorOptions.check.js +1 -1
  157. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  158. package/types.d.ts +225 -157
  159. package/lib/ModuleSourceTypesConstants.js +0 -117
  160. package/lib/dependencies/CssIcssFromIdentifierDependency.js +0 -124
  161. package/lib/dependencies/CssIcssGlobalIdentifierDependency.js +0 -48
  162. package/lib/dependencies/CssIcssLocalIdentifierDependency.js +0 -61
  163. package/lib/dependencies/CssIcssSelfLocalIdentifierDependency.js +0 -190
  164. package/lib/util/jsonParseEvenBetterErrors.js +0 -10
  165. package/schemas/plugins/css/CssAutoGeneratorOptions.check.d.ts +0 -7
  166. package/schemas/plugins/css/CssAutoGeneratorOptions.check.js +0 -6
  167. package/schemas/plugins/css/CssAutoGeneratorOptions.json +0 -3
  168. package/schemas/plugins/css/CssAutoParserOptions.check.d.ts +0 -7
  169. package/schemas/plugins/css/CssAutoParserOptions.check.js +0 -6
  170. package/schemas/plugins/css/CssAutoParserOptions.json +0 -3
  171. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.d.ts +0 -7
  172. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.js +0 -6
  173. package/schemas/plugins/css/CssGlobalGeneratorOptions.json +0 -3
  174. package/schemas/plugins/css/CssGlobalParserOptions.check.d.ts +0 -7
  175. package/schemas/plugins/css/CssGlobalParserOptions.check.js +0 -6
  176. package/schemas/plugins/css/CssGlobalParserOptions.json +0 -3
@@ -15,6 +15,8 @@ const { cachedSetProperty } = require("./util/cleverMerge");
15
15
  const { createFakeHook } = require("./util/deprecation");
16
16
  const { join } = require("./util/fs");
17
17
 
18
+ /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
19
+ /** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
18
20
  /** @typedef {import("./ContextModule").ContextModuleOptions} ContextModuleOptions */
19
21
  /** @typedef {import("./ContextModule").ResolveDependenciesCallback} ResolveDependenciesCallback */
20
22
  /** @typedef {import("./ModuleFactory").ModuleFactoryCreateData} ModuleFactoryCreateData */
@@ -22,7 +24,7 @@ const { join } = require("./util/fs");
22
24
  /** @typedef {import("./ResolverFactory")} ResolverFactory */
23
25
  /** @typedef {import("./dependencies/ContextDependency")} ContextDependency */
24
26
  /** @typedef {import("./dependencies/ContextDependency").ContextOptions} ContextOptions */
25
- /** @typedef {import("enhanced-resolve").ResolveRequest} ResolveRequest */
27
+
26
28
  /**
27
29
  * @template T
28
30
  * @typedef {import("./util/deprecation").FakeHook<T>} FakeHook<T>
@@ -36,9 +38,9 @@ const { join } = require("./util/fs");
36
38
  * @property {string} context
37
39
  * @property {string} request
38
40
  * @property {ModuleFactoryCreateData["resolveOptions"]} resolveOptions
39
- * @property {LazySet<string>} fileDependencies
40
- * @property {LazySet<string>} missingDependencies
41
- * @property {LazySet<string>} contextDependencies
41
+ * @property {FileSystemDependencies} fileDependencies
42
+ * @property {FileSystemDependencies} missingDependencies
43
+ * @property {FileSystemDependencies} contextDependencies
42
44
  * @property {ContextDependency[]} dependencies
43
45
  */
44
46
 
@@ -5,6 +5,7 @@
5
5
 
6
6
  "use strict";
7
7
 
8
+ const { SyncWaterfallHook } = require("tapable");
8
9
  const {
9
10
  JAVASCRIPT_MODULE_TYPE_AUTO,
10
11
  JAVASCRIPT_MODULE_TYPE_DYNAMIC,
@@ -32,6 +33,7 @@ const createHash = require("./util/createHash");
32
33
  /** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */
33
34
  /** @typedef {import("./javascript/JavascriptParser").Range} Range */
34
35
  /** @typedef {import("./logging/Logger").Logger} Logger */
36
+ /** @typedef {import("./Compilation")} Compilation */
35
37
 
36
38
  /** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */
37
39
  /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive | RuntimeValue>} CodeValue */
@@ -42,7 +44,7 @@ const createHash = require("./util/createHash");
42
44
  * @property {string[]=} contextDependencies
43
45
  * @property {string[]=} missingDependencies
44
46
  * @property {string[]=} buildDependencies
45
- * @property {string| (() => string)=} version
47
+ * @property {string | (() => string)=} version
46
48
  */
47
49
 
48
50
  /** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
@@ -180,7 +182,7 @@ const stringifyObj = (
180
182
  code = `{${keys
181
183
  .map((key) => {
182
184
  const code = obj[key];
183
- return `${JSON.stringify(key)}:${toCode(
185
+ return `${key === "__proto__" ? '["__proto__"]' : JSON.stringify(key)}:${toCode(
184
186
  code,
185
187
  parser,
186
188
  valueCacheVersions,
@@ -330,7 +332,30 @@ const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
330
332
  );
331
333
  const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
332
334
 
335
+ /**
336
+ * @typedef {object} DefinePluginHooks
337
+ * @property {SyncWaterfallHook<[Record<string, CodeValue>]>} definitions
338
+ */
339
+
340
+ /** @type {WeakMap<Compilation, DefinePluginHooks>} */
341
+ const compilationHooksMap = new WeakMap();
342
+
333
343
  class DefinePlugin {
344
+ /**
345
+ * @param {Compilation} compilation the compilation
346
+ * @returns {DefinePluginHooks} the attached hooks
347
+ */
348
+ static getCompilationHooks(compilation) {
349
+ let hooks = compilationHooksMap.get(compilation);
350
+ if (hooks === undefined) {
351
+ hooks = {
352
+ definitions: new SyncWaterfallHook(["definitions"])
353
+ };
354
+ compilationHooksMap.set(compilation, hooks);
355
+ }
356
+ return hooks;
357
+ }
358
+
334
359
  /**
335
360
  * Create a new define plugin
336
361
  * @param {Record<string, CodeValue>} definitions A map of global object definitions
@@ -358,6 +383,12 @@ class DefinePlugin {
358
383
  PLUGIN_NAME,
359
384
  (compilation, { normalModuleFactory }) => {
360
385
  const definitions = this.definitions;
386
+ const hooks = DefinePlugin.getCompilationHooks(compilation);
387
+
388
+ hooks.definitions.tap(PLUGIN_NAME, (previousDefinitions) => ({
389
+ ...previousDefinitions,
390
+ ...definitions
391
+ }));
361
392
 
362
393
  /**
363
394
  * @type {Map<string, Set<string>>}
@@ -505,7 +536,7 @@ class DefinePlugin {
505
536
  return;
506
537
  }
507
538
  /** @type {Record<string, CodeValue>} */
508
- const obj = {};
539
+ const obj = Object.create(null);
509
540
  const finalSet = finalByNestedKey.get(nested);
510
541
  for (const { id } of destructed) {
511
542
  const fullKey = `${nested}.${id}`;
@@ -7,7 +7,10 @@
7
7
 
8
8
  const { OriginalSource, RawSource } = require("webpack-sources");
9
9
  const Module = require("./Module");
10
- const { JS_TYPES } = require("./ModuleSourceTypesConstants");
10
+ const {
11
+ JAVASCRIPT_TYPE,
12
+ JAVASCRIPT_TYPES
13
+ } = require("./ModuleSourceTypeConstants");
11
14
  const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
12
15
  const RuntimeGlobals = require("./RuntimeGlobals");
13
16
  const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
@@ -80,7 +83,7 @@ class DelegatedModule extends Module {
80
83
  * @returns {SourceTypes} types available (do not mutate)
81
84
  */
82
85
  getSourceTypes() {
83
- return JS_TYPES;
86
+ return JAVASCRIPT_TYPES;
84
87
  }
85
88
 
86
89
  /**
@@ -177,9 +180,9 @@ class DelegatedModule extends Module {
177
180
 
178
181
  const sources = new Map();
179
182
  if (this.useSourceMap || this.useSimpleSourceMap) {
180
- sources.set("javascript", new OriginalSource(str, this.identifier()));
183
+ sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier()));
181
184
  } else {
182
- sources.set("javascript", new RawSource(str));
185
+ sources.set(JAVASCRIPT_TYPE, new RawSource(str));
183
186
  }
184
187
 
185
188
  return {
package/lib/DllModule.js CHANGED
@@ -7,7 +7,10 @@
7
7
 
8
8
  const { RawSource } = require("webpack-sources");
9
9
  const Module = require("./Module");
10
- const { JS_TYPES } = require("./ModuleSourceTypesConstants");
10
+ const {
11
+ JAVASCRIPT_TYPE,
12
+ JAVASCRIPT_TYPES
13
+ } = require("./ModuleSourceTypeConstants");
11
14
  const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
12
15
  const RuntimeGlobals = require("./RuntimeGlobals");
13
16
  const makeSerializable = require("./util/makeSerializable");
@@ -53,7 +56,7 @@ class DllModule extends Module {
53
56
  * @returns {SourceTypes} types available (do not mutate)
54
57
  */
55
58
  getSourceTypes() {
56
- return JS_TYPES;
59
+ return JAVASCRIPT_TYPES;
57
60
  }
58
61
 
59
62
  /**
@@ -92,7 +95,7 @@ class DllModule extends Module {
92
95
  codeGeneration(context) {
93
96
  const sources = new Map();
94
97
  sources.set(
95
- "javascript",
98
+ JAVASCRIPT_TYPE,
96
99
  new RawSource(`module.exports = ${RuntimeGlobals.require};`)
97
100
  );
98
101
  return {
@@ -54,7 +54,7 @@ const validate = createSchemaValidation(
54
54
  * @returns {Env} parsed environment variables object
55
55
  */
56
56
  function parse(src) {
57
- const obj = /** @type {Env} */ ({});
57
+ const obj = /** @type {Env} */ (Object.create(null));
58
58
 
59
59
  // Convert buffer to string
60
60
  let lines = src.toString();
@@ -174,7 +174,7 @@ function expandValue(value, processEnv, runningParsed) {
174
174
  */
175
175
  function expand(options) {
176
176
  // for use with progressive expansion
177
- const runningParsed = /** @type {Env} */ ({});
177
+ const runningParsed = /** @type {Env} */ (Object.create(null));
178
178
  const processEnv = options.processEnv;
179
179
 
180
180
  // dotenv.config() ran before this so the assumption is process.env has already been set
@@ -183,7 +183,8 @@ function expand(options) {
183
183
 
184
184
  // short-circuit scenario: process.env was already set prior to the file value
185
185
  value =
186
- processEnv[key] && processEnv[key] !== value
186
+ Object.prototype.hasOwnProperty.call(processEnv, key) &&
187
+ processEnv[key] !== value
187
188
  ? /** @type {string} */ (processEnv[key])
188
189
  : expandValue(value, processEnv, runningParsed);
189
190
 
@@ -332,7 +333,7 @@ class DotenvPlugin {
332
333
 
333
334
  // Parse all files and merge (later files override earlier ones)
334
335
  // Similar to Vite's implementation
335
- const parsed = /** @type {Env} */ ({});
336
+ const parsed = /** @type {Env} */ (Object.create(null));
336
337
 
337
338
  for (const content of contents) {
338
339
  if (!content) continue;
@@ -422,7 +423,7 @@ class DotenvPlugin {
422
423
  // Make a copy of process.env so that dotenv-expand doesn't modify global process.env
423
424
  const processEnv = { ...process.env };
424
425
  expand({ parsed, processEnv });
425
- const env = /** @type {Env} */ ({});
426
+ const env = /** @type {Env} */ (Object.create(null));
426
427
 
427
428
  // Get all keys from parser and process.env
428
429
  const keys = [...Object.keys(parsed), ...Object.keys(process.env)];
@@ -430,7 +431,11 @@ class DotenvPlugin {
430
431
  // Prioritize actual env variables from `process.env`, fallback to parsed
431
432
  for (const key of keys) {
432
433
  if (prefixes.some((prefix) => key.startsWith(prefix))) {
433
- env[key] = process.env[key] ? process.env[key] : parsed[key];
434
+ env[key] =
435
+ Object.prototype.hasOwnProperty.call(process.env, key) &&
436
+ process.env[key]
437
+ ? process.env[key]
438
+ : parsed[key];
434
439
  }
435
440
  }
436
441
 
@@ -1346,11 +1346,11 @@ class ExportInfo {
1346
1346
  export: rawTarget.export,
1347
1347
  deferred: Boolean(
1348
1348
  rawTarget.connection.dependency &&
1349
- ImportPhaseUtils.isDefer(
1350
- /** @type {HarmonyImportDependency} */ (
1351
- rawTarget.connection.dependency
1352
- ).phase
1353
- )
1349
+ ImportPhaseUtils.isDefer(
1350
+ /** @type {HarmonyImportDependency} */ (
1351
+ rawTarget.connection.dependency
1352
+ ).phase
1353
+ )
1354
1354
  )
1355
1355
  };
1356
1356
  for (;;) {
@@ -14,8 +14,9 @@ const Module = require("./Module");
14
14
  const {
15
15
  CSS_IMPORT_TYPES,
16
16
  CSS_URL_TYPES,
17
- JS_TYPES
18
- } = require("./ModuleSourceTypesConstants");
17
+ JAVASCRIPT_TYPE,
18
+ JAVASCRIPT_TYPES
19
+ } = require("./ModuleSourceTypeConstants");
19
20
  const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
20
21
  const RuntimeGlobals = require("./RuntimeGlobals");
21
22
  const Template = require("./Template");
@@ -86,7 +87,7 @@ const RUNTIME_REQUIREMENTS_FOR_SCRIPT = new Set([RuntimeGlobals.loadScript]);
86
87
  const RUNTIME_REQUIREMENTS_FOR_MODULE = new Set([
87
88
  RuntimeGlobals.definePropertyGetters
88
89
  ]);
89
- const EMPTY_RUNTIME_REQUIREMENTS = new Set([]);
90
+ const EMPTY_RUNTIME_REQUIREMENTS = new Set();
90
91
 
91
92
  /**
92
93
  * @param {string | string[]} variableName the variable name or path
@@ -655,7 +656,7 @@ class ExternalModule extends Module {
655
656
  return CSS_IMPORT_TYPES;
656
657
  }
657
658
 
658
- return JS_TYPES;
659
+ return JAVASCRIPT_TYPES;
659
660
  }
660
661
 
661
662
  /**
@@ -979,7 +980,7 @@ class ExternalModule extends Module {
979
980
  case "asset": {
980
981
  const sources = new Map();
981
982
  sources.set(
982
- "javascript",
983
+ JAVASCRIPT_TYPE,
983
984
  new RawSource(`module.exports = ${JSON.stringify(request)};`)
984
985
  );
985
986
  const data = new Map();
@@ -1064,11 +1065,11 @@ class ExternalModule extends Module {
1064
1065
  const sources = new Map();
1065
1066
  if (this.useSourceMap || this.useSimpleSourceMap) {
1066
1067
  sources.set(
1067
- "javascript",
1068
+ JAVASCRIPT_TYPE,
1068
1069
  new OriginalSource(sourceString, this.identifier())
1069
1070
  );
1070
1071
  } else {
1071
- sources.set("javascript", new RawSource(sourceString));
1072
+ sources.set(JAVASCRIPT_TYPE, new RawSource(sourceString));
1072
1073
  }
1073
1074
 
1074
1075
  let runtimeRequirements = sourceData.runtimeRequirements;
@@ -26,7 +26,7 @@ const { cachedSetProperty, resolveByProperty } = require("./util/cleverMerge");
26
26
  /** @typedef {import("./ModuleFactory").ModuleFactoryCreateDataContextInfo} ModuleFactoryCreateDataContextInfo */
27
27
  /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
28
28
 
29
- /** @typedef {((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import('enhanced-resolve').ResolveRequest) => void) => void)} ExternalItemFunctionDataGetResolveCallbackResult */
29
+ /** @typedef {((context: string, request: string, callback: (err?: Error | null, result?: string | false, resolveRequest?: import("enhanced-resolve").ResolveRequest) => void) => void)} ExternalItemFunctionDataGetResolveCallbackResult */
30
30
  /** @typedef {((context: string, request: string) => Promise<string>)} ExternalItemFunctionDataGetResolveResult */
31
31
  /** @typedef {(options?: ResolveOptions) => ExternalItemFunctionDataGetResolveCallbackResult | ExternalItemFunctionDataGetResolveResult} ExternalItemFunctionDataGetResolve */
32
32
 
@@ -939,7 +939,7 @@ const mergeSets = (a, b) => {
939
939
  * Finding file or directory to manage
940
940
  * @param {string} managedPath path that is managing by {@link FileSystemInfo}
941
941
  * @param {string} path path to file or directory
942
- * @returns {string|null} managed item
942
+ * @returns {string | null} managed item
943
943
  * @example
944
944
  * getManagedItem(
945
945
  * '/Users/user/my-project/node_modules/',
package/lib/Generator.js CHANGED
@@ -5,6 +5,8 @@
5
5
 
6
6
  "use strict";
7
7
 
8
+ const { JAVASCRIPT_TYPE } = require("./ModuleSourceTypeConstants");
9
+
8
10
  /** @typedef {import("webpack-sources").Source} Source */
9
11
  /** @typedef {import("./ChunkGraph")} ChunkGraph */
10
12
  /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
@@ -13,6 +15,7 @@
13
15
  /** @typedef {import("./Module").CodeGenerationResultData} CodeGenerationResultData */
14
16
  /** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
15
17
  /** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
18
+ /** @typedef {import("./Module").SourceType} SourceType */
16
19
  /** @typedef {import("./Module").SourceTypes} SourceTypes */
17
20
  /** @typedef {import("./ModuleGraph")} ModuleGraph */
18
21
  /** @typedef {import("./NormalModule")} NormalModule */
@@ -30,7 +33,7 @@
30
33
  * @property {RuntimeSpec} runtime the runtime
31
34
  * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
32
35
  * @property {CodeGenerationResults=} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
33
- * @property {string} type which kind of code should be generated
36
+ * @property {SourceType} type which kind of code should be generated
34
37
  * @property {() => CodeGenerationResultData=} getData get access to the code generation data
35
38
  */
36
39
 
@@ -52,7 +55,7 @@
52
55
 
53
56
  class Generator {
54
57
  /**
55
- * @param {Record<string, Generator>} map map of types
58
+ * @param {{ [key in SourceType]?: Generator }} map map of types
56
59
  * @returns {ByTypeGenerator} generator by type
57
60
  */
58
61
  static byType(map) {
@@ -75,7 +78,7 @@ class Generator {
75
78
  /**
76
79
  * @abstract
77
80
  * @param {NormalModule} module the module
78
- * @param {string=} type source type
81
+ * @param {SourceType=} type source type
79
82
  * @returns {number} estimate size of the module
80
83
  */
81
84
  getSize(module, type) {
@@ -138,12 +141,12 @@ function generateError(error, module, generateContext) {
138
141
 
139
142
  class ByTypeGenerator extends Generator {
140
143
  /**
141
- * @param {Record<string, Generator>} map map of types
144
+ * @param {{ [key in SourceType]?: Generator }} map map of types
142
145
  */
143
146
  constructor(map) {
144
147
  super();
145
148
  this.map = map;
146
- this._types = new Set(Object.keys(map));
149
+ this._types = /** @type {SourceTypes} */ (new Set(Object.keys(map)));
147
150
  /** @type {GenerateErrorFn | undefined} */
148
151
  this.generateError = generateError.bind(this);
149
152
  }
@@ -158,10 +161,10 @@ class ByTypeGenerator extends Generator {
158
161
 
159
162
  /**
160
163
  * @param {NormalModule} module the module
161
- * @param {string=} type source type
164
+ * @param {SourceType=} type source type
162
165
  * @returns {number} estimate size of the module
163
166
  */
164
- getSize(module, type = "javascript") {
167
+ getSize(module, type = JAVASCRIPT_TYPE) {
165
168
  const t = type;
166
169
  const generator = this.map[t];
167
170
  return generator ? generator.getSize(module, t) : 0;
@@ -6,6 +6,10 @@
6
6
  "use strict";
7
7
 
8
8
  const WebpackError = require("./WebpackError");
9
+ const makeSerializable = require("./util/makeSerializable");
10
+
11
+ /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
12
+ /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
9
13
 
10
14
  /**
11
15
  * @template T
@@ -22,18 +26,43 @@ class HookWebpackError extends WebpackError {
22
26
  * @param {string} hook name of hook
23
27
  */
24
28
  constructor(error, hook) {
25
- super(error.message);
29
+ super(error ? error.message : undefined, error ? { cause: error } : {});
26
30
 
27
- this.name = "HookWebpackError";
28
31
  this.hook = hook;
29
32
  this.error = error;
33
+ this.name = "HookWebpackError";
30
34
  this.hideStack = true;
31
- this.details = `caused by plugins in ${hook}\n${error.stack}`;
35
+ this.stack += `\n-- inner error --\n${error ? error.stack : ""}`;
36
+ this.details = `caused by plugins in ${hook}\n${error ? error.stack : ""}`;
37
+ }
38
+
39
+ /**
40
+ * @param {ObjectSerializerContext} context context
41
+ */
42
+ serialize(context) {
43
+ const { write } = context;
44
+
45
+ write(this.error);
46
+ write(this.hook);
32
47
 
33
- this.stack += `\n-- inner error --\n${error.stack}`;
48
+ super.serialize(context);
49
+ }
50
+
51
+ /**
52
+ * @param {ObjectDeserializerContext} context context
53
+ */
54
+ deserialize(context) {
55
+ const { read } = context;
56
+
57
+ this.error = read();
58
+ this.hook = read();
59
+
60
+ super.deserialize(context);
34
61
  }
35
62
  }
36
63
 
64
+ makeSerializable(HookWebpackError, "webpack/lib/HookWebpackError");
65
+
37
66
  module.exports = HookWebpackError;
38
67
 
39
68
  /**
@@ -19,6 +19,7 @@ const {
19
19
  const NormalModule = require("./NormalModule");
20
20
  const RuntimeGlobals = require("./RuntimeGlobals");
21
21
  const WebpackError = require("./WebpackError");
22
+ const { chunkHasCss } = require("./css/CssModulesPlugin");
22
23
  const ConstDependency = require("./dependencies/ConstDependency");
23
24
  const ImportMetaHotAcceptDependency = require("./dependencies/ImportMetaHotAcceptDependency");
24
25
  const ImportMetaHotDeclineDependency = require("./dependencies/ImportMetaHotDeclineDependency");
@@ -817,6 +818,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
817
818
  filename,
818
819
  { removedChunkIds, removedModules, updatedChunkIds, assetInfo }
819
820
  ] of hotUpdateMainContentByFilename) {
821
+ /** @type {{c: ChunkId[], r: ChunkId[], m: ModuleId[], css?: {r: ChunkId[]}}} */
820
822
  const hotUpdateMainJson = {
821
823
  c: [...updatedChunkIds],
822
824
  r: [...removedChunkIds],
@@ -833,6 +835,26 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
833
835
  ]
834
836
  };
835
837
 
838
+ // Build CSS removed chunks list (chunks in updatedChunkIds that no longer have CSS)
839
+ /** @type {ChunkId[]} */
840
+ const cssRemovedChunkIds = [];
841
+ if (compilation.options.experiments.css) {
842
+ for (const chunkId of updatedChunkIds) {
843
+ for (const /** @type {Chunk} */ chunk of compilation.chunks) {
844
+ if (chunk.id === chunkId) {
845
+ if (!chunkHasCss(chunk, chunkGraph)) {
846
+ cssRemovedChunkIds.push(chunkId);
847
+ }
848
+ break;
849
+ }
850
+ }
851
+ }
852
+ }
853
+
854
+ if (cssRemovedChunkIds.length > 0) {
855
+ hotUpdateMainJson.css = { r: cssRemovedChunkIds };
856
+ }
857
+
836
858
  const source = new RawSource(
837
859
  (filename.endsWith(".json") ? "" : "export default ") +
838
860
  JSON.stringify(hotUpdateMainJson)
@@ -52,7 +52,7 @@ class ManifestPlugin {
52
52
  constructor(options) {
53
53
  validate(options);
54
54
 
55
- /** @type {ManifestPluginOptions & Required<Omit<ManifestPluginOptions, "filter" | "generate">>} */
55
+ /** @type {ManifestPluginOptions & Required<Omit<ManifestPluginOptions, "filter" | "generate">>} */
56
56
  this.options = {
57
57
  filename: "manifest.json",
58
58
  prefix: "[publicpath]",
package/lib/Module.js CHANGED
@@ -9,7 +9,11 @@ const util = require("util");
9
9
  const ChunkGraph = require("./ChunkGraph");
10
10
  const DependenciesBlock = require("./DependenciesBlock");
11
11
  const ModuleGraph = require("./ModuleGraph");
12
- const { JS_TYPES } = require("./ModuleSourceTypesConstants");
12
+ const {
13
+ JAVASCRIPT_TYPE,
14
+ UNKNOWN_TYPE
15
+ } = require("./ModuleSourceTypeConstants");
16
+ const { JAVASCRIPT_TYPES } = require("./ModuleSourceTypeConstants");
13
17
  const RuntimeGlobals = require("./RuntimeGlobals");
14
18
  const { first } = require("./util/SetHelpers");
15
19
  const { compareChunksById } = require("./util/comparators");
@@ -24,12 +28,14 @@ const makeSerializable = require("./util/makeSerializable");
24
28
  /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
25
29
  /** @typedef {import("./Compilation")} Compilation */
26
30
  /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
31
+ /** @typedef {import("./Compilation").FileSystemDependencies} FileSystemDependencies */
27
32
  /** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */
28
33
  /** @typedef {import("./ConcatenationScope")} ConcatenationScope */
29
34
  /** @typedef {import("./Dependency")} Dependency */
30
35
  /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
31
36
  /** @typedef {import("./DependencyTemplate").CssData} CssData */
32
37
  /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
38
+ /** @typedef {import("./ModuleSourceTypeConstants").AllTypes} AllTypes */
33
39
  /** @typedef {import("./FileSystemInfo")} FileSystemInfo */
34
40
  /** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
35
41
  /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
@@ -70,7 +76,9 @@ const makeSerializable = require("./util/makeSerializable");
70
76
  * @property {string=} type the type of source that should be generated
71
77
  */
72
78
 
73
- /** @typedef {ReadonlySet<string>} SourceTypes */
79
+ /** @typedef {AllTypes} KnownSourceType */
80
+ /** @typedef {KnownSourceType | string} SourceType */
81
+ /** @typedef {ReadonlySet<SourceType>} SourceTypes */
74
82
 
75
83
  // TODO webpack 6: compilation will be required in CodeGenerationContext
76
84
  /**
@@ -80,6 +88,7 @@ const makeSerializable = require("./util/makeSerializable");
80
88
  * @property {ModuleGraph} moduleGraph the module graph
81
89
  * @property {ChunkGraph} chunkGraph the chunk graph
82
90
  * @property {RuntimeSpec} runtime the runtimes code should be generated for
91
+ * @property {RuntimeSpec[]} runtimes all runtimes code should be generated for
83
92
  * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
84
93
  * @property {CodeGenerationResults | undefined} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
85
94
  * @property {Compilation=} compilation the compilation
@@ -103,7 +112,7 @@ const makeSerializable = require("./util/makeSerializable");
103
112
 
104
113
  /**
105
114
  * @typedef {object} CodeGenerationResult
106
- * @property {Map<string, Source>} sources the resulting sources for all source types
115
+ * @property {Map<SourceType, Source>} sources the resulting sources for all source types
107
116
  * @property {CodeGenerationResultData=} data the resulting data for all source types
108
117
  * @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements
109
118
  * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided)
@@ -126,12 +135,10 @@ const makeSerializable = require("./util/makeSerializable");
126
135
  * @property {boolean=} sideEffectFree
127
136
  * @property {boolean=} isCSSModule
128
137
  * @property {Record<string, string>=} jsIncompatibleExports
129
- * @property {Record<string, string>=} exportsFinalName
130
- * @property {string=} factoryExportsBinding
138
+ * @property {Map<RuntimeSpec, Record<string, string>>=} exportsFinalNameByRuntime
139
+ * @property {Map<RuntimeSpec, string>=} exportsSourceByRuntime
131
140
  */
132
141
 
133
- /** @typedef {LazySet<string>} FileSystemDependencies */
134
-
135
142
  /**
136
143
  * @typedef {object} KnownBuildInfo
137
144
  * @property {boolean=} cacheable
@@ -188,7 +195,8 @@ const EMPTY_RESOLVE_OPTIONS = {};
188
195
 
189
196
  let debugId = 1000;
190
197
 
191
- const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]);
198
+ /** @type {SourceTypes} */
199
+ const DEFAULT_TYPES_UNKNOWN = new Set([UNKNOWN_TYPE]);
192
200
 
193
201
  const deprecatedNeedRebuild = util.deprecate(
194
202
  /**
@@ -839,8 +847,8 @@ class Module extends DependenciesBlock {
839
847
 
840
848
  /**
841
849
  * @deprecated Use needBuild instead
842
- * @param {Map<string, number|null>} fileTimestamps timestamps of files
843
- * @param {Map<string, number|null>} contextTimestamps timestamps of directories
850
+ * @param {Map<string, number | null>} fileTimestamps timestamps of files
851
+ * @param {Map<string, number | null>} contextTimestamps timestamps of directories
844
852
  * @returns {boolean} true, if the module needs a rebuild
845
853
  */
846
854
  needRebuild(fileTimestamps, contextTimestamps) {
@@ -928,7 +936,7 @@ class Module extends DependenciesBlock {
928
936
  if (this.source === Module.prototype.source) {
929
937
  return DEFAULT_TYPES_UNKNOWN;
930
938
  }
931
- return JS_TYPES;
939
+ return JAVASCRIPT_TYPES;
932
940
  }
933
941
 
934
942
  /**
@@ -936,10 +944,10 @@ class Module extends DependenciesBlock {
936
944
  * @deprecated Use codeGeneration() instead
937
945
  * @param {DependencyTemplates} dependencyTemplates the dependency templates
938
946
  * @param {RuntimeTemplate} runtimeTemplate the runtime template
939
- * @param {string=} type the type of source that should be generated
947
+ * @param {SourceType=} type the type of source that should be generated
940
948
  * @returns {Source} generated source
941
949
  */
942
- source(dependencyTemplates, runtimeTemplate, type = "javascript") {
950
+ source(dependencyTemplates, runtimeTemplate, type = JAVASCRIPT_TYPE) {
943
951
  if (this.codeGeneration === Module.prototype.codeGeneration) {
944
952
  const AbstractMethodError = require("./AbstractMethodError");
945
953
 
@@ -957,6 +965,7 @@ class Module extends DependenciesBlock {
957
965
  moduleGraph: chunkGraph.moduleGraph,
958
966
  chunkGraph,
959
967
  runtime: undefined,
968
+ runtimes: [],
960
969
  codeGenerationResults: undefined
961
970
  };
962
971
  const sources = this.codeGeneration(codeGenContext).sources;
@@ -964,7 +973,7 @@ class Module extends DependenciesBlock {
964
973
  return /** @type {Source} */ (
965
974
  type
966
975
  ? sources.get(type)
967
- : sources.get(/** @type {string} */ (first(this.getSourceTypes())))
976
+ : sources.get(/** @type {SourceType} */ (first(this.getSourceTypes())))
968
977
  );
969
978
  }
970
979
 
@@ -1019,7 +1028,7 @@ class Module extends DependenciesBlock {
1019
1028
  // Best override this method
1020
1029
  const sources = new Map();
1021
1030
  for (const type of this.getSourceTypes()) {
1022
- if (type !== "unknown") {
1031
+ if (type !== UNKNOWN_TYPE) {
1023
1032
  sources.set(
1024
1033
  type,
1025
1034
  this.source(
@@ -17,7 +17,7 @@ const makeSerializable = require("./util/makeSerializable");
17
17
  class ModuleBuildError extends WebpackError {
18
18
  /**
19
19
  * @param {string | ErrorWithHideStack} err error thrown
20
- * @param {{from?: string|null}} info additional info
20
+ * @param {{from?: string | null}} info additional info
21
21
  */
22
22
  constructor(err, { from = null } = {}) {
23
23
  let message = "Module build failed";
@@ -15,7 +15,7 @@ const makeSerializable = require("./util/makeSerializable");
15
15
  class ModuleError extends WebpackError {
16
16
  /**
17
17
  * @param {Error} err error thrown
18
- * @param {{from?: string|null}} info additional info
18
+ * @param {{from?: string | null}} info additional info
19
19
  */
20
20
  constructor(err, { from = null } = {}) {
21
21
  let message = "Module Error";