webpack 5.102.1 → 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 (220) hide show
  1. package/README.md +121 -134
  2. package/hot/dev-server.js +18 -3
  3. package/hot/emitter-event-target.js +7 -0
  4. package/hot/lazy-compilation-node.js +45 -29
  5. package/hot/lazy-compilation-universal.js +18 -0
  6. package/hot/lazy-compilation-web.js +15 -5
  7. package/hot/load-http.js +7 -0
  8. package/hot/only-dev-server.js +19 -4
  9. package/lib/APIPlugin.js +6 -0
  10. package/lib/Chunk.js +1 -1
  11. package/lib/ChunkGraph.js +9 -7
  12. package/lib/ChunkGroup.js +8 -5
  13. package/lib/CleanPlugin.js +6 -3
  14. package/lib/CodeGenerationResults.js +2 -1
  15. package/lib/CompatibilityPlugin.js +28 -2
  16. package/lib/Compilation.js +58 -21
  17. package/lib/Compiler.js +3 -3
  18. package/lib/ConcatenationScope.js +0 -15
  19. package/lib/ContextModule.js +6 -3
  20. package/lib/ContextModuleFactory.js +6 -4
  21. package/lib/CssModule.js +6 -1
  22. package/lib/DefinePlugin.js +45 -14
  23. package/lib/DelegatedModule.js +7 -4
  24. package/lib/Dependency.js +8 -1
  25. package/lib/DependencyTemplate.js +1 -0
  26. package/lib/DllModule.js +6 -3
  27. package/lib/DotenvPlugin.js +462 -0
  28. package/lib/EnvironmentPlugin.js +19 -16
  29. package/lib/EvalSourceMapDevToolPlugin.js +16 -0
  30. package/lib/ExportsInfo.js +6 -2
  31. package/lib/ExternalModule.js +28 -35
  32. package/lib/ExternalModuleFactoryPlugin.js +11 -9
  33. package/lib/ExternalsPlugin.js +2 -1
  34. package/lib/FileSystemInfo.js +1 -1
  35. package/lib/Generator.js +10 -7
  36. package/lib/HookWebpackError.js +33 -4
  37. package/lib/HotModuleReplacementPlugin.js +22 -0
  38. package/lib/ManifestPlugin.js +235 -0
  39. package/lib/Module.js +27 -15
  40. package/lib/ModuleBuildError.js +1 -1
  41. package/lib/ModuleError.js +1 -1
  42. package/lib/ModuleFilenameHelpers.js +1 -1
  43. package/lib/ModuleGraph.js +29 -13
  44. package/lib/ModuleGraphConnection.js +2 -2
  45. package/lib/ModuleSourceTypeConstants.js +189 -0
  46. package/lib/ModuleTypeConstants.js +1 -4
  47. package/lib/ModuleWarning.js +1 -1
  48. package/lib/MultiCompiler.js +1 -1
  49. package/lib/NodeStuffPlugin.js +424 -116
  50. package/lib/NormalModule.js +23 -20
  51. package/lib/NormalModuleFactory.js +7 -10
  52. package/lib/Parser.js +1 -1
  53. package/lib/RawModule.js +7 -4
  54. package/lib/RuntimeGlobals.js +22 -4
  55. package/lib/RuntimeModule.js +1 -1
  56. package/lib/RuntimePlugin.js +27 -6
  57. package/lib/RuntimeTemplate.js +120 -57
  58. package/lib/SourceMapDevToolPlugin.js +26 -1
  59. package/lib/Template.js +17 -6
  60. package/lib/TemplatedPathPlugin.js +5 -6
  61. package/lib/WebpackError.js +0 -1
  62. package/lib/WebpackOptionsApply.js +67 -15
  63. package/lib/asset/AssetBytesGenerator.js +16 -12
  64. package/lib/asset/AssetGenerator.js +31 -26
  65. package/lib/asset/AssetSourceGenerator.js +16 -12
  66. package/lib/asset/RawDataUrlModule.js +6 -3
  67. package/lib/buildChunkGraph.js +4 -2
  68. package/lib/cache/PackFileCacheStrategy.js +6 -5
  69. package/lib/cli.js +2 -43
  70. package/lib/config/browserslistTargetHandler.js +24 -0
  71. package/lib/config/defaults.js +226 -61
  72. package/lib/config/normalization.js +4 -3
  73. package/lib/config/target.js +11 -0
  74. package/lib/container/ContainerEntryModule.js +6 -3
  75. package/lib/container/FallbackModule.js +6 -3
  76. package/lib/container/RemoteModule.js +1 -3
  77. package/lib/css/CssGenerator.js +304 -76
  78. package/lib/css/CssLoadingRuntimeModule.js +14 -4
  79. package/lib/css/CssMergeStyleSheetsRuntimeModule.js +56 -0
  80. package/lib/css/CssModulesPlugin.js +72 -67
  81. package/lib/css/CssParser.js +1726 -732
  82. package/lib/css/walkCssTokens.js +128 -11
  83. package/lib/dependencies/CachedConstDependency.js +24 -10
  84. package/lib/dependencies/CommonJsImportsParserPlugin.js +0 -9
  85. package/lib/dependencies/CommonJsPlugin.js +12 -0
  86. package/lib/dependencies/CommonJsRequireContextDependency.js +1 -1
  87. package/lib/dependencies/ContextDependencyHelpers.js +2 -2
  88. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +3 -1
  89. package/lib/dependencies/CssIcssExportDependency.js +389 -12
  90. package/lib/dependencies/CssIcssImportDependency.js +114 -51
  91. package/lib/dependencies/CssIcssSymbolDependency.js +31 -33
  92. package/lib/dependencies/CssImportDependency.js +17 -6
  93. package/lib/dependencies/CssUrlDependency.js +3 -2
  94. package/lib/dependencies/DynamicExports.js +7 -7
  95. package/lib/dependencies/ExternalModuleDependency.js +7 -4
  96. package/lib/dependencies/ExternalModuleInitFragment.js +3 -2
  97. package/lib/dependencies/ExternalModuleInitFragmentDependency.js +96 -0
  98. package/lib/dependencies/HarmonyAcceptDependency.js +6 -1
  99. package/lib/dependencies/HarmonyAcceptImportDependency.js +2 -1
  100. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +12 -1
  101. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +35 -23
  102. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +13 -9
  103. package/lib/dependencies/HarmonyExports.js +4 -4
  104. package/lib/dependencies/HarmonyImportDependency.js +28 -27
  105. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +28 -69
  106. package/lib/dependencies/HarmonyImportSideEffectDependency.js +4 -3
  107. package/lib/dependencies/HarmonyImportSpecifierDependency.js +10 -8
  108. package/lib/dependencies/ImportDependency.js +8 -2
  109. package/lib/dependencies/ImportEagerDependency.js +6 -3
  110. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +1 -1
  111. package/lib/dependencies/ImportMetaPlugin.js +154 -9
  112. package/lib/dependencies/ImportParserPlugin.js +21 -23
  113. package/lib/dependencies/ImportPhase.js +121 -0
  114. package/lib/dependencies/ImportWeakDependency.js +6 -3
  115. package/lib/dependencies/LocalModulesHelpers.js +3 -3
  116. package/lib/dependencies/ModuleDependency.js +5 -1
  117. package/lib/dependencies/ModuleHotAcceptDependency.js +1 -1
  118. package/lib/dependencies/WorkerPlugin.js +2 -2
  119. package/lib/dependencies/getFunctionExpression.js +1 -1
  120. package/lib/esm/ExportWebpackRequireRuntimeModule.js +1 -8
  121. package/lib/esm/ModuleChunkFormatPlugin.js +5 -4
  122. package/lib/hmr/HotModuleReplacement.runtime.js +2 -1
  123. package/lib/hmr/LazyCompilationPlugin.js +5 -3
  124. package/lib/ids/IdHelpers.js +20 -8
  125. package/lib/index.js +6 -0
  126. package/lib/javascript/ChunkHelpers.js +16 -5
  127. package/lib/javascript/JavascriptGenerator.js +105 -104
  128. package/lib/javascript/JavascriptModulesPlugin.js +80 -37
  129. package/lib/javascript/JavascriptParser.js +161 -44
  130. package/lib/json/JsonGenerator.js +5 -4
  131. package/lib/json/JsonParser.js +9 -2
  132. package/lib/library/AbstractLibraryPlugin.js +1 -1
  133. package/lib/library/AmdLibraryPlugin.js +4 -1
  134. package/lib/library/ExportPropertyLibraryPlugin.js +4 -1
  135. package/lib/library/ModuleLibraryPlugin.js +41 -23
  136. package/lib/library/SystemLibraryPlugin.js +8 -1
  137. package/lib/library/UmdLibraryPlugin.js +2 -2
  138. package/lib/logging/Logger.js +5 -4
  139. package/lib/logging/createConsoleLogger.js +2 -2
  140. package/lib/node/NodeTargetPlugin.js +9 -1
  141. package/lib/node/ReadFileCompileWasmPlugin.js +0 -2
  142. package/lib/optimize/ConcatenatedModule.js +208 -167
  143. package/lib/optimize/ModuleConcatenationPlugin.js +5 -4
  144. package/lib/optimize/SideEffectsFlagPlugin.js +3 -2
  145. package/lib/optimize/SplitChunksPlugin.js +60 -46
  146. package/lib/rules/RuleSetCompiler.js +1 -1
  147. package/lib/runtime/AsyncModuleRuntimeModule.js +28 -18
  148. package/lib/runtime/AutoPublicPathRuntimeModule.js +8 -3
  149. package/lib/runtime/GetChunkFilenameRuntimeModule.js +3 -2
  150. package/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +89 -55
  151. package/lib/schemes/HttpUriPlugin.js +78 -7
  152. package/lib/serialization/AggregateErrorSerializer.js +1 -2
  153. package/lib/serialization/ObjectMiddleware.js +0 -2
  154. package/lib/serialization/SingleItemMiddleware.js +1 -1
  155. package/lib/sharing/ConsumeSharedModule.js +1 -1
  156. package/lib/sharing/ConsumeSharedPlugin.js +5 -3
  157. package/lib/sharing/ProvideSharedModule.js +1 -1
  158. package/lib/sharing/resolveMatchedConfigs.js +15 -9
  159. package/lib/sharing/utils.js +1 -1
  160. package/lib/stats/DefaultStatsFactoryPlugin.js +8 -5
  161. package/lib/stats/DefaultStatsPresetPlugin.js +1 -1
  162. package/lib/stats/DefaultStatsPrinterPlugin.js +1 -1
  163. package/lib/util/StringXor.js +1 -1
  164. package/lib/util/URLAbsoluteSpecifier.js +2 -2
  165. package/lib/util/binarySearchBounds.js +2 -2
  166. package/lib/util/comparators.js +54 -76
  167. package/lib/util/compileBooleanMatcher.js +78 -6
  168. package/lib/util/createHash.js +20 -199
  169. package/lib/util/deprecation.js +1 -1
  170. package/lib/util/deterministicGrouping.js +6 -3
  171. package/lib/util/fs.js +75 -75
  172. package/lib/util/hash/BatchedHash.js +10 -9
  173. package/lib/util/hash/BulkUpdateHash.js +138 -0
  174. package/lib/util/hash/DebugHash.js +75 -0
  175. package/lib/util/hash/hash-digest.js +216 -0
  176. package/lib/util/identifier.js +82 -17
  177. package/lib/util/internalSerializables.js +2 -6
  178. package/lib/util/runtime.js +3 -3
  179. package/lib/util/source.js +2 -2
  180. package/lib/wasm/EnableWasmLoadingPlugin.js +10 -4
  181. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +3 -2
  182. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +11 -7
  183. package/lib/wasm-sync/WebAssemblyGenerator.js +9 -6
  184. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +11 -6
  185. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +6 -2
  186. package/lib/web/FetchCompileWasmPlugin.js +0 -2
  187. package/lib/webpack.js +85 -82
  188. package/module.d.ts +5 -0
  189. package/package.json +34 -28
  190. package/schemas/WebpackOptions.check.js +1 -1
  191. package/schemas/WebpackOptions.json +160 -101
  192. package/schemas/plugins/{css/CssAutoParserOptions.check.d.ts → ManifestPlugin.check.d.ts} +1 -1
  193. package/schemas/plugins/ManifestPlugin.check.js +6 -0
  194. package/schemas/plugins/ManifestPlugin.json +98 -0
  195. package/schemas/plugins/SourceMapDevToolPlugin.check.js +1 -1
  196. package/schemas/plugins/SourceMapDevToolPlugin.json +16 -3
  197. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  198. package/schemas/plugins/container/ContainerReferencePlugin.json +4 -1
  199. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  200. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  201. package/schemas/plugins/container/ModuleFederationPlugin.json +4 -1
  202. package/schemas/plugins/css/CssModuleGeneratorOptions.check.js +1 -1
  203. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  204. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  205. package/schemas/plugins/json/JsonModulesPluginParser.check.js +1 -1
  206. package/types.d.ts +771 -436
  207. package/lib/ModuleSourceTypesConstants.js +0 -123
  208. package/lib/dependencies/CssLocalIdentifierDependency.js +0 -250
  209. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +0 -112
  210. package/schemas/plugins/css/CssAutoGeneratorOptions.check.d.ts +0 -7
  211. package/schemas/plugins/css/CssAutoGeneratorOptions.check.js +0 -6
  212. package/schemas/plugins/css/CssAutoGeneratorOptions.json +0 -3
  213. package/schemas/plugins/css/CssAutoParserOptions.check.js +0 -6
  214. package/schemas/plugins/css/CssAutoParserOptions.json +0 -3
  215. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.d.ts +0 -7
  216. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.js +0 -6
  217. package/schemas/plugins/css/CssGlobalGeneratorOptions.json +0 -3
  218. package/schemas/plugins/css/CssGlobalParserOptions.check.d.ts +0 -7
  219. package/schemas/plugins/css/CssGlobalParserOptions.check.js +0 -6
  220. package/schemas/plugins/css/CssGlobalParserOptions.json +0 -3
@@ -11,15 +11,24 @@ const Template = require("./Template");
11
11
  const {
12
12
  getOutgoingAsyncModules
13
13
  } = require("./async-modules/AsyncModuleHelpers");
14
+ const { ImportPhaseUtils } = require("./dependencies/ImportPhase");
14
15
  const {
15
16
  getMakeDeferredNamespaceModeFromExportsType,
16
17
  getOptimizedDeferredModule
17
18
  } = require("./runtime/MakeDeferredNamespaceObjectRuntime");
18
19
  const { equals } = require("./util/ArrayHelpers");
19
20
  const compileBooleanMatcher = require("./util/compileBooleanMatcher");
21
+ const memoize = require("./util/memoize");
20
22
  const propertyAccess = require("./util/propertyAccess");
21
23
  const { forEachRuntime, subtractRuntime } = require("./util/runtime");
22
24
 
25
+ const getHarmonyImportDependency = memoize(() =>
26
+ require("./dependencies/HarmonyImportDependency")
27
+ );
28
+ const getImportDependency = memoize(() =>
29
+ require("./dependencies/ImportDependency")
30
+ );
31
+
23
32
  /** @typedef {import("./config/defaults").OutputNormalizedWithDefaults} OutputOptions */
24
33
  /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
25
34
  /** @typedef {import("./Chunk")} Chunk */
@@ -32,6 +41,8 @@ const { forEachRuntime, subtractRuntime } = require("./util/runtime");
32
41
  /** @typedef {import("./ModuleGraph")} ModuleGraph */
33
42
  /** @typedef {import("./RequestShortener")} RequestShortener */
34
43
  /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
44
+ /** @typedef {import("./dependencies/ImportPhase").ImportPhaseType} ImportPhaseType */
45
+ /** @typedef {import("./NormalModuleFactory").ModuleDependency} ModuleDependency */
35
46
 
36
47
  /**
37
48
  * @param {Module} module the module
@@ -116,6 +127,10 @@ class RuntimeTemplate {
116
127
  return this.outputOptions.environment.const;
117
128
  }
118
129
 
130
+ supportsMethodShorthand() {
131
+ return this.outputOptions.environment.methodShorthand;
132
+ }
133
+
119
134
  supportsArrowFunction() {
120
135
  return this.outputOptions.environment.arrowFunction;
121
136
  }
@@ -617,6 +632,7 @@ class RuntimeTemplate {
617
632
  * @param {string} options.message a message for the comment
618
633
  * @param {boolean=} options.strict if the current module is in strict esm mode
619
634
  * @param {boolean=} options.weak if the dependency is weak (will create a nice error message)
635
+ * @param {Dependency} options.dependency dependency
620
636
  * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
621
637
  * @returns {string} the promise expression
622
638
  */
@@ -628,6 +644,7 @@ class RuntimeTemplate {
628
644
  message,
629
645
  strict,
630
646
  weak,
647
+ dependency,
631
648
  runtimeRequirements
632
649
  }) {
633
650
  if (!module) {
@@ -684,42 +701,45 @@ class RuntimeTemplate {
684
701
  type: "statements"
685
702
  })} } `;
686
703
  }
687
- const moduleIdExpr = this.moduleId({
688
- module,
689
- chunkGraph,
690
- request,
691
- weak
692
- });
693
704
  const exportsType = module.getExportsType(chunkGraph.moduleGraph, strict);
694
- let fakeType = 16;
695
- switch (exportsType) {
696
- case "namespace":
705
+
706
+ const isModuleDeferred =
707
+ (dependency instanceof getHarmonyImportDependency() ||
708
+ dependency instanceof getImportDependency()) &&
709
+ ImportPhaseUtils.isDefer(dependency.phase) &&
710
+ !(/** @type {BuildMeta} */ (module.buildMeta).async);
711
+
712
+ if (isModuleDeferred) {
713
+ runtimeRequirements.add(RuntimeGlobals.makeDeferredNamespaceObject);
714
+ const mode = getMakeDeferredNamespaceModeFromExportsType(exportsType);
715
+ const asyncDeps = Array.from(
716
+ getOutgoingAsyncModules(chunkGraph.moduleGraph, module),
717
+ (m) => chunkGraph.getModuleId(m)
718
+ ).filter((id) => id !== null);
719
+ if (asyncDeps.length) {
697
720
  if (header) {
698
- const rawModule = this.moduleRaw({
699
- module,
700
- chunkGraph,
701
- request,
702
- weak,
703
- runtimeRequirements
704
- });
705
721
  appending = `.then(${this.basicFunction(
706
722
  "",
707
- `${header}return ${rawModule};`
723
+ `${header}return ${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)});`
708
724
  )})`;
709
725
  } else {
710
726
  runtimeRequirements.add(RuntimeGlobals.require);
711
- appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
727
+ appending = `.then(${this.returningFunction(`${RuntimeGlobals.deferredModuleAsyncTransitiveDependencies}(${JSON.stringify(asyncDeps)})`)})`;
712
728
  }
713
- break;
714
- case "dynamic":
715
- fakeType |= 4;
716
- /* fall through */
717
- case "default-with-named":
718
- fakeType |= 2;
719
- /* fall through */
720
- case "default-only":
721
- runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
722
- if (chunkGraph.moduleGraph.isAsync(module)) {
729
+ appending += `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
730
+ } else if (header) {
731
+ appending = `.then(${this.basicFunction(
732
+ "",
733
+ `${header}return ${RuntimeGlobals.makeDeferredNamespaceObject}(${comment}${idExpr}, ${mode});`
734
+ )})`;
735
+ } else {
736
+ runtimeRequirements.add(RuntimeGlobals.require);
737
+ appending = `.then(${RuntimeGlobals.makeDeferredNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${mode}))`;
738
+ }
739
+ } else {
740
+ let fakeType = 16;
741
+ switch (exportsType) {
742
+ case "namespace":
723
743
  if (header) {
724
744
  const rawModule = this.moduleRaw({
725
745
  module,
@@ -736,23 +756,56 @@ class RuntimeTemplate {
736
756
  runtimeRequirements.add(RuntimeGlobals.require);
737
757
  appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
738
758
  }
739
- appending += `.then(${this.returningFunction(
740
- `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
741
- "m"
742
- )})`;
743
- } else {
744
- fakeType |= 1;
745
- if (header) {
746
- const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
747
- appending = `.then(${this.basicFunction(
748
- "",
749
- `${header}return ${returnExpression};`
759
+ break;
760
+ case "dynamic":
761
+ fakeType |= 4;
762
+ /* fall through */
763
+ case "default-with-named":
764
+ fakeType |= 2;
765
+ /* fall through */
766
+ case "default-only":
767
+ runtimeRequirements.add(RuntimeGlobals.createFakeNamespaceObject);
768
+ if (chunkGraph.moduleGraph.isAsync(module)) {
769
+ if (header) {
770
+ const rawModule = this.moduleRaw({
771
+ module,
772
+ chunkGraph,
773
+ request,
774
+ weak,
775
+ runtimeRequirements
776
+ });
777
+ appending = `.then(${this.basicFunction(
778
+ "",
779
+ `${header}return ${rawModule};`
780
+ )})`;
781
+ } else {
782
+ runtimeRequirements.add(RuntimeGlobals.require);
783
+ appending = `.then(${RuntimeGlobals.require}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}))`;
784
+ }
785
+ appending += `.then(${this.returningFunction(
786
+ `${RuntimeGlobals.createFakeNamespaceObject}(m, ${fakeType})`,
787
+ "m"
750
788
  )})`;
751
789
  } else {
752
- appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
790
+ fakeType |= 1;
791
+ if (header) {
792
+ const moduleIdExpr = this.moduleId({
793
+ module,
794
+ chunkGraph,
795
+ request,
796
+ weak
797
+ });
798
+ const returnExpression = `${RuntimeGlobals.createFakeNamespaceObject}(${moduleIdExpr}, ${fakeType})`;
799
+ appending = `.then(${this.basicFunction(
800
+ "",
801
+ `${header}return ${returnExpression};`
802
+ )})`;
803
+ } else {
804
+ appending = `.then(${RuntimeGlobals.createFakeNamespaceObject}.bind(${RuntimeGlobals.require}, ${comment}${idExpr}, ${fakeType}))`;
805
+ }
753
806
  }
754
- }
755
- break;
807
+ break;
808
+ }
756
809
  }
757
810
 
758
811
  return `${promise || "Promise.resolve()"}${appending}`;
@@ -806,7 +859,7 @@ class RuntimeTemplate {
806
859
  * @param {Module} options.originModule module in which the statement is emitted
807
860
  * @param {boolean=} options.weak true, if this is a weak dependency
808
861
  * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
809
- * @param {boolean=} options.defer if set, the module will be deferred
862
+ * @param {ModuleDependency} options.dependency module dependency
810
863
  * @returns {[string, string]} the import statement and the compat statement
811
864
  */
812
865
  importStatement({
@@ -818,7 +871,7 @@ class RuntimeTemplate {
818
871
  importVar,
819
872
  originModule,
820
873
  weak,
821
- defer,
874
+ dependency,
822
875
  runtimeRequirements
823
876
  }) {
824
877
  if (!module) {
@@ -866,15 +919,22 @@ class RuntimeTemplate {
866
919
  );
867
920
  runtimeRequirements.add(RuntimeGlobals.require);
868
921
  let importContent;
869
- if (defer && !(/** @type {BuildMeta} */ (module.buildMeta).async)) {
922
+
923
+ const isModuleDeferred =
924
+ (dependency instanceof getHarmonyImportDependency() ||
925
+ dependency instanceof getImportDependency()) &&
926
+ ImportPhaseUtils.isDefer(dependency.phase) &&
927
+ !(/** @type {BuildMeta} */ (module.buildMeta).async);
928
+
929
+ if (isModuleDeferred) {
870
930
  /** @type {Set<Module>} */
871
931
  const outgoingAsyncModules = getOutgoingAsyncModules(moduleGraph, module);
872
932
 
873
933
  importContent = `/* deferred harmony import */ ${optDeclaration}${importVar} = ${getOptimizedDeferredModule(
874
- this,
875
- exportsType,
876
934
  moduleId,
877
- Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod))
935
+ exportsType,
936
+ Array.from(outgoingAsyncModules, (mod) => chunkGraph.getModuleId(mod)),
937
+ runtimeRequirements
878
938
  )};\n`;
879
939
 
880
940
  return [importContent, ""];
@@ -900,7 +960,7 @@ class RuntimeTemplate {
900
960
  * @param {string} options.request the request
901
961
  * @param {string | string[]} options.exportName the export name
902
962
  * @param {Module} options.originModule the origin module
903
- * @param {boolean|undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
963
+ * @param {boolean | undefined} options.asiSafe true, if location is safe for ASI, a bracket can be emitted
904
964
  * @param {boolean} options.isCall true, if expression will be called
905
965
  * @param {boolean | null} options.callContext when false, call context will not be preserved
906
966
  * @param {boolean} options.defaultInterop when true and accessing the default exports, interop code will be generated
@@ -908,7 +968,7 @@ class RuntimeTemplate {
908
968
  * @param {InitFragment<GenerateContext>[]} options.initFragments init fragments will be added here
909
969
  * @param {RuntimeSpec} options.runtime runtime for which this code will be generated
910
970
  * @param {RuntimeRequirements} options.runtimeRequirements if set, will be filled with runtime requirements
911
- * @param {boolean=} options.defer if true, the module will be deferred.
971
+ * @param {ModuleDependency} options.dependency module dependency
912
972
  * @returns {string} expression
913
973
  */
914
974
  exportFromImport({
@@ -926,7 +986,7 @@ class RuntimeTemplate {
926
986
  initFragments,
927
987
  runtime,
928
988
  runtimeRequirements,
929
- defer
989
+ dependency
930
990
  }) {
931
991
  if (!module) {
932
992
  return this.missingModule({
@@ -942,13 +1002,16 @@ class RuntimeTemplate {
942
1002
  (originModule.buildMeta).strictHarmonyModule
943
1003
  );
944
1004
 
945
- const isDeferred =
946
- defer && !(/** @type {BuildMeta} */ (module.buildMeta).async);
1005
+ const isModuleDeferred =
1006
+ (dependency instanceof getHarmonyImportDependency() ||
1007
+ dependency instanceof getImportDependency()) &&
1008
+ ImportPhaseUtils.isDefer(dependency.phase) &&
1009
+ !(/** @type {BuildMeta} */ (module.buildMeta).async);
947
1010
 
948
1011
  if (defaultInterop) {
949
1012
  // when the defaultInterop is used (when a ESM imports a CJS module),
950
1013
  if (exportName.length > 0 && exportName[0] === "default") {
951
- if (isDeferred && exportsType !== "namespace") {
1014
+ if (isModuleDeferred && exportsType !== "namespace") {
952
1015
  const exportsInfo = moduleGraph.getExportsInfo(module);
953
1016
  const name = exportName.slice(1);
954
1017
  const used = exportsInfo.getUsedName(name, runtime);
@@ -1002,7 +1065,7 @@ class RuntimeTemplate {
1002
1065
  ) {
1003
1066
  return "/* __esModule */true";
1004
1067
  }
1005
- } else if (isDeferred) {
1068
+ } else if (isModuleDeferred) {
1006
1069
  // now exportName.length is 0
1007
1070
  // fall through to the end of this function, create the namespace there.
1008
1071
  } else if (
@@ -1045,7 +1108,7 @@ class RuntimeTemplate {
1045
1108
  ? ""
1046
1109
  : `${Template.toNormalComment(propertyAccess(exportName))} `;
1047
1110
  const access = `${importVar}${
1048
- isDeferred ? ".a" : ""
1111
+ isModuleDeferred ? ".a" : ""
1049
1112
  }${comment}${propertyAccess(used)}`;
1050
1113
  if (isCall && callContext === false) {
1051
1114
  return asiSafe
@@ -1056,7 +1119,7 @@ class RuntimeTemplate {
1056
1119
  }
1057
1120
  return access;
1058
1121
  }
1059
- if (isDeferred) {
1122
+ if (isModuleDeferred) {
1060
1123
  initFragments.push(
1061
1124
  new InitFragment(
1062
1125
  `var ${importVar}_deferred_namespace_cache;\n`,
@@ -20,6 +20,7 @@ const { makePathsAbsolute } = require("./util/identifier");
20
20
  /** @typedef {import("webpack-sources").MapOptions} MapOptions */
21
21
  /** @typedef {import("webpack-sources").Source} Source */
22
22
  /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */
23
+ /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").Rules} Rules */
23
24
  /** @typedef {import("./CacheFacade").ItemCacheFacade} ItemCacheFacade */
24
25
  /** @typedef {import("./Chunk")} Chunk */
25
26
  /** @typedef {import("./Compilation").Asset} Asset */
@@ -433,6 +434,25 @@ class SourceMapDevToolPlugin {
433
434
  moduleToSourceNameMapping.get(m)
434
435
  );
435
436
  sourceMap.sources = /** @type {string[]} */ (moduleFilenames);
437
+ sourceMap.ignoreList = options.ignoreList
438
+ ? sourceMap.sources.reduce(
439
+ /** @type {(acc: number[], sourceName: string, idx: number) => number[]} */ (
440
+ (acc, sourceName, idx) => {
441
+ const rule = /** @type {Rules} */ (
442
+ options.ignoreList
443
+ );
444
+ if (
445
+ ModuleFilenameHelpers.matchPart(sourceName, rule)
446
+ ) {
447
+ acc.push(idx);
448
+ }
449
+ return acc;
450
+ }
451
+ ),
452
+ []
453
+ )
454
+ : [];
455
+
436
456
  if (options.noSources) {
437
457
  sourceMap.sourcesContent = undefined;
438
458
  }
@@ -476,7 +496,12 @@ class SourceMapDevToolPlugin {
476
496
  if (options.debugIds) {
477
497
  const debugId = generateDebugId(source, sourceMap.file);
478
498
  sourceMap.debugId = debugId;
479
- currentSourceMappingURLComment = `\n//# debugId=${debugId}${currentSourceMappingURLComment}`;
499
+
500
+ const debugIdComment = `\n//# debugId=${debugId}`;
501
+ currentSourceMappingURLComment =
502
+ currentSourceMappingURLComment
503
+ ? `${debugIdComment}${currentSourceMappingURLComment}`
504
+ : debugIdComment;
480
505
  }
481
506
 
482
507
  const sourceMapString = JSON.stringify(sourceMap);
package/lib/Template.js CHANGED
@@ -280,7 +280,7 @@ class Template {
280
280
  /**
281
281
  * @param {ChunkRenderContext} renderContext render context
282
282
  * @param {Module[]} modules modules to render (should be ordered by identifier)
283
- * @param {(module: Module) => Source | null} renderModule function to render a module
283
+ * @param {(module: Module, renderInArray?: boolean) => Source | null} renderModule function to render a module
284
284
  * @param {string=} prefix applying prefix strings
285
285
  * @returns {Source | null} rendered chunk modules in a Source object or null if no modules
286
286
  */
@@ -290,12 +290,20 @@ class Template {
290
290
  if (modules.length === 0) {
291
291
  return null;
292
292
  }
293
+ /** @type {{ id: ModuleId, module: Module }[]} */
294
+ const modulesWithId = modules.map((m) => ({
295
+ id: /** @type {ModuleId} */ (chunkGraph.getModuleId(m)),
296
+ module: m
297
+ }));
298
+ const bounds = Template.getModulesArrayBounds(modulesWithId);
299
+ const renderInObject = bounds === false;
300
+
293
301
  /** @type {{ id: ModuleId, source: Source | "false" }[]} */
294
- const allModules = modules.map((module) => ({
295
- id: /** @type {ModuleId} */ (chunkGraph.getModuleId(module)),
296
- source: renderModule(module) || "false"
302
+ const allModules = modulesWithId.map(({ id, module }) => ({
303
+ id,
304
+ source: renderModule(module, renderInObject) || "false"
297
305
  }));
298
- const bounds = Template.getModulesArrayBounds(allModules);
306
+
299
307
  if (bounds) {
300
308
  // Render a spare array
301
309
  const minId = bounds[0];
@@ -332,7 +340,9 @@ class Template {
332
340
  if (i !== 0) {
333
341
  source.add(",\n");
334
342
  }
335
- source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`);
343
+ source.add(
344
+ `\n/***/ ${JSON.stringify(module.id)}${renderContext.runtimeTemplate.supportsMethodShorthand() && module.source !== "false" ? "" : ":"}\n`
345
+ );
336
346
  source.add(module.source);
337
347
  }
338
348
  source.add(`\n\n${prefix}}`);
@@ -363,6 +373,7 @@ class Template {
363
373
  moduleGraph: renderContext.moduleGraph,
364
374
  runtimeTemplate: renderContext.runtimeTemplate,
365
375
  runtime: renderContext.chunk.runtime,
376
+ runtimes: [renderContext.chunk.runtime],
366
377
  codeGenerationResults
367
378
  });
368
379
  if (!codeGenResult) continue;
@@ -20,10 +20,7 @@ const { parseResource } = require("./util/identifier");
20
20
 
21
21
  const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
22
22
 
23
- /**
24
- * @param {string | number} id id
25
- * @returns {string | number} result
26
- */
23
+ /** @type {PathData["prepareId"]} */
27
24
  const prepareId = (id) => {
28
25
  if (typeof id !== "string") return id;
29
26
 
@@ -303,7 +300,7 @@ const replacePathVariables = (path, data, assetInfo) => {
303
300
  const module = data.module;
304
301
 
305
302
  const idReplacer = replacer(() =>
306
- prepareId(
303
+ (data.prepareId || prepareId)(
307
304
  module instanceof Module
308
305
  ? /** @type {ModuleId} */
309
306
  (/** @type {ChunkGraph} */ (chunkGraph).getModuleId(module))
@@ -353,7 +350,9 @@ const replacePathVariables = (path, data, assetInfo) => {
353
350
  if (typeof data.runtime === "string") {
354
351
  replacements.set(
355
352
  "runtime",
356
- replacer(() => prepareId(/** @type {string} */ (data.runtime)))
353
+ replacer(() =>
354
+ (data.prepareId || prepareId)(/** @type {string} */ (data.runtime))
355
+ )
357
356
  );
358
357
  } else {
359
358
  replacements.set("runtime", replacer("_"));
@@ -21,7 +21,6 @@ class WebpackError extends Error {
21
21
  * @param {{ cause?: unknown }} options error options
22
22
  */
23
23
  constructor(message, options = {}) {
24
- // @ts-expect-error ES2018 doesn't `Error.cause`, but it can be used by developers
25
24
  super(message, options);
26
25
 
27
26
  /** @type {string=} */
@@ -18,6 +18,7 @@ const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin");
18
18
 
19
19
  const JavascriptMetaInfoPlugin = require("./JavascriptMetaInfoPlugin");
20
20
 
21
+ const NodeStuffPlugin = require("./NodeStuffPlugin");
21
22
  const OptionsApply = require("./OptionsApply");
22
23
 
23
24
  const RecordIdsPlugin = require("./RecordIdsPlugin");
@@ -109,7 +110,15 @@ class WebpackOptionsApply extends OptionsApply {
109
110
  if (options.externalsPresets.node) {
110
111
  const NodeTargetPlugin = require("./node/NodeTargetPlugin");
111
112
 
112
- new NodeTargetPlugin().apply(compiler);
113
+ // Some older versions of Node.js don't support all built-in modules via import, only via `require`,
114
+ // but it seems like there shouldn't be a warning here since these versions are rarely used in real applications
115
+ new NodeTargetPlugin(
116
+ options.output.module &&
117
+ compiler.platform.node === null &&
118
+ compiler.platform.web === null
119
+ ? "module-import"
120
+ : "node-commonjs"
121
+ ).apply(compiler);
113
122
 
114
123
  // Handle external CSS `@import` and `url()`
115
124
  if (options.experiments.css) {
@@ -126,7 +135,9 @@ class WebpackOptionsApply extends OptionsApply {
126
135
  if (dependencyType === "url") {
127
136
  return callback(null, `asset ${request}`);
128
137
  } else if (
129
- dependencyType === "css-import" &&
138
+ (dependencyType === "css-import" ||
139
+ dependencyType === "css-import-local-module" ||
140
+ dependencyType === "css-import-global-module") &&
130
141
  options.experiments.css
131
142
  ) {
132
143
  return callback(null, `css-import ${request}`);
@@ -149,7 +160,9 @@ class WebpackOptionsApply extends OptionsApply {
149
160
  if (dependencyType === "url") {
150
161
  return callback(null, `asset ${request}`);
151
162
  } else if (
152
- dependencyType === "css-import" &&
163
+ (dependencyType === "css-import" ||
164
+ dependencyType === "css-import-local-module" ||
165
+ dependencyType === "css-import-global-module") &&
153
166
  options.experiments.css
154
167
  ) {
155
168
  return callback(null, `css-import ${request}`);
@@ -294,6 +307,14 @@ class WebpackOptionsApply extends OptionsApply {
294
307
  ).apply(compiler);
295
308
  }
296
309
 
310
+ if (options.dotenv) {
311
+ const DotenvPlugin = require("./DotenvPlugin");
312
+
313
+ new DotenvPlugin(
314
+ typeof options.dotenv === "boolean" ? {} : options.dotenv
315
+ ).apply(compiler);
316
+ }
317
+
297
318
  if (options.devtool) {
298
319
  if (options.devtool.includes("source-map")) {
299
320
  const hidden = options.devtool.includes("hidden");
@@ -387,6 +408,39 @@ class WebpackOptionsApply extends OptionsApply {
387
408
  typeof options.experiments.lazyCompilation === "object"
388
409
  ? options.experiments.lazyCompilation
389
410
  : {};
411
+ const isUniversalTarget =
412
+ options.output.module &&
413
+ compiler.platform.node === null &&
414
+ compiler.platform.web === null;
415
+
416
+ if (isUniversalTarget) {
417
+ const emitter = require.resolve("../hot/emitter-event-target.js");
418
+
419
+ const NormalModuleReplacementPlugin = require("./NormalModuleReplacementPlugin");
420
+
421
+ // Override emitter that using `EventEmitter` to `EventTarget`
422
+ // TODO webpack6 - migrate to `EventTarget` by default
423
+ new NormalModuleReplacementPlugin(/emitter(\.js)?$/, (result) => {
424
+ if (
425
+ /webpack[/\\]hot|webpack-dev-server[/\\]client|webpack-hot-middleware[/\\]client/.test(
426
+ result.context
427
+ )
428
+ ) {
429
+ result.request = emitter;
430
+ }
431
+
432
+ return result;
433
+ }).apply(compiler);
434
+ }
435
+
436
+ const backend = require.resolve(
437
+ isUniversalTarget
438
+ ? "../hot/lazy-compilation-universal.js"
439
+ : `../hot/lazy-compilation-${
440
+ options.externalsPresets.node ? "node" : "web"
441
+ }.js`
442
+ );
443
+
390
444
  new LazyCompilationPlugin({
391
445
  backend:
392
446
  typeof lazyOptions.backend === "function"
@@ -394,12 +448,7 @@ class WebpackOptionsApply extends OptionsApply {
394
448
  : require("./hmr/lazyCompilationBackend")({
395
449
  ...lazyOptions.backend,
396
450
  client:
397
- (lazyOptions.backend && lazyOptions.backend.client) ||
398
- require.resolve(
399
- `../hot/lazy-compilation-${
400
- options.externalsPresets.node ? "node" : "web"
401
- }.js`
402
- )
451
+ (lazyOptions.backend && lazyOptions.backend.client) || backend
403
452
  }),
404
453
  entries: !lazyOptions || lazyOptions.entries !== false,
405
454
  imports: !lazyOptions || lazyOptions.imports !== false,
@@ -444,11 +493,11 @@ class WebpackOptionsApply extends OptionsApply {
444
493
  }
445
494
  new CommonJsPlugin().apply(compiler);
446
495
  new LoaderPlugin().apply(compiler);
447
- if (options.node !== false) {
448
- const NodeStuffPlugin = require("./NodeStuffPlugin");
449
-
450
- new NodeStuffPlugin(options.node).apply(compiler);
451
- }
496
+ new NodeStuffPlugin({
497
+ global: options.node ? options.node.global : false,
498
+ __dirname: options.node ? options.node.__dirname : false,
499
+ __filename: options.node ? options.node.__filename : false
500
+ }).apply(compiler);
452
501
  new APIPlugin().apply(compiler);
453
502
  new ExportsInfoApiPlugin().apply(compiler);
454
503
  new WebpackIsIncludedPlugin().apply(compiler);
@@ -667,8 +716,11 @@ class WebpackOptionsApply extends OptionsApply {
667
716
  if (options.optimization.nodeEnv) {
668
717
  const DefinePlugin = require("./DefinePlugin");
669
718
 
719
+ const defValue = JSON.stringify(options.optimization.nodeEnv);
720
+
670
721
  new DefinePlugin({
671
- "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv)
722
+ "process.env.NODE_ENV": defValue,
723
+ "import.meta.env.NODE_ENV": defValue
672
724
  }).apply(compiler);
673
725
  }
674
726
  if (options.optimization.minimize) {