webpack 5.59.0 → 5.76.0

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

Potentially problematic release.


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

Files changed (236) hide show
  1. package/README.md +22 -24
  2. package/bin/webpack.js +0 -0
  3. package/hot/dev-server.js +17 -4
  4. package/hot/lazy-compilation-node.js +3 -1
  5. package/hot/poll.js +1 -1
  6. package/hot/signal.js +1 -1
  7. package/lib/APIPlugin.js +33 -0
  8. package/lib/BannerPlugin.js +13 -5
  9. package/lib/Cache.js +1 -1
  10. package/lib/CacheFacade.js +4 -11
  11. package/lib/Chunk.js +6 -3
  12. package/lib/ChunkGraph.js +94 -8
  13. package/lib/ChunkGroup.js +1 -1
  14. package/lib/CleanPlugin.js +81 -20
  15. package/lib/Compilation.js +188 -93
  16. package/lib/Compiler.js +87 -18
  17. package/lib/ConstPlugin.js +2 -2
  18. package/lib/ContextModule.js +142 -51
  19. package/lib/ContextModuleFactory.js +65 -25
  20. package/lib/DelegatedModule.js +1 -1
  21. package/lib/DelegatedModuleFactoryPlugin.js +1 -1
  22. package/lib/Dependency.js +17 -0
  23. package/lib/DependencyTemplate.js +9 -0
  24. package/lib/DependencyTemplates.js +1 -1
  25. package/lib/DllModule.js +1 -1
  26. package/lib/DllReferencePlugin.js +1 -1
  27. package/lib/EntryOptionPlugin.js +2 -0
  28. package/lib/ErrorHelpers.js +2 -2
  29. package/lib/EvalDevToolModulePlugin.js +16 -1
  30. package/lib/EvalSourceMapDevToolPlugin.js +25 -4
  31. package/lib/ExportsInfo.js +5 -5
  32. package/lib/ExternalModule.js +94 -54
  33. package/lib/ExternalModuleFactoryPlugin.js +5 -5
  34. package/lib/FileSystemInfo.js +124 -58
  35. package/lib/Generator.js +3 -0
  36. package/lib/HookWebpackError.js +1 -1
  37. package/lib/HotModuleReplacementPlugin.js +3 -1
  38. package/lib/LoaderOptionsPlugin.js +1 -1
  39. package/lib/Module.js +28 -4
  40. package/lib/ModuleFilenameHelpers.js +8 -4
  41. package/lib/ModuleHashingError.js +29 -0
  42. package/lib/MultiCompiler.js +1 -1
  43. package/lib/MultiWatching.js +1 -1
  44. package/lib/NodeStuffPlugin.js +13 -3
  45. package/lib/NormalModule.js +51 -33
  46. package/lib/NormalModuleFactory.js +42 -37
  47. package/lib/ProgressPlugin.js +4 -5
  48. package/lib/RawModule.js +1 -1
  49. package/lib/RuntimeGlobals.js +29 -1
  50. package/lib/RuntimeModule.js +1 -1
  51. package/lib/RuntimePlugin.js +84 -1
  52. package/lib/RuntimeTemplate.js +114 -2
  53. package/lib/Template.js +3 -2
  54. package/lib/TemplatedPathPlugin.js +48 -23
  55. package/lib/WatchIgnorePlugin.js +19 -7
  56. package/lib/Watching.js +33 -19
  57. package/lib/WebpackOptionsApply.js +79 -11
  58. package/lib/asset/AssetGenerator.js +228 -71
  59. package/lib/asset/AssetModulesPlugin.js +3 -0
  60. package/lib/asset/AssetParser.js +1 -0
  61. package/lib/asset/AssetSourceGenerator.js +31 -6
  62. package/lib/asset/AssetSourceParser.js +1 -0
  63. package/lib/asset/RawDataUrlModule.js +148 -0
  64. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -4
  65. package/lib/buildChunkGraph.js +38 -7
  66. package/lib/cache/PackFileCacheStrategy.js +15 -8
  67. package/lib/cache/ResolverCachePlugin.js +90 -29
  68. package/lib/cli.js +44 -3
  69. package/lib/config/browserslistTargetHandler.js +41 -6
  70. package/lib/config/defaults.js +123 -19
  71. package/lib/config/normalization.js +10 -2
  72. package/lib/config/target.js +10 -0
  73. package/lib/container/ContainerEntryModule.js +8 -5
  74. package/lib/container/FallbackModule.js +4 -4
  75. package/lib/container/ModuleFederationPlugin.js +2 -0
  76. package/lib/container/RemoteModule.js +4 -2
  77. package/lib/container/RemoteRuntimeModule.js +8 -7
  78. package/lib/css/CssExportsGenerator.js +139 -0
  79. package/lib/css/CssGenerator.js +109 -0
  80. package/lib/css/CssLoadingRuntimeModule.js +442 -0
  81. package/lib/css/CssModulesPlugin.js +462 -0
  82. package/lib/css/CssParser.js +618 -0
  83. package/lib/css/walkCssTokens.js +659 -0
  84. package/lib/debug/ProfilingPlugin.js +24 -21
  85. package/lib/dependencies/AMDRequireDependency.js +6 -6
  86. package/lib/dependencies/CommonJsExportsParserPlugin.js +1 -2
  87. package/lib/dependencies/CommonJsFullRequireDependency.js +5 -1
  88. package/lib/dependencies/CommonJsImportsParserPlugin.js +344 -61
  89. package/lib/dependencies/CommonJsRequireContextDependency.js +6 -2
  90. package/lib/dependencies/CommonJsRequireDependency.js +2 -1
  91. package/lib/dependencies/ContextDependency.js +16 -2
  92. package/lib/dependencies/ContextDependencyHelpers.js +21 -8
  93. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +4 -1
  94. package/lib/dependencies/ContextElementDependency.js +25 -3
  95. package/lib/dependencies/CreateScriptUrlDependency.js +12 -0
  96. package/lib/dependencies/CssExportDependency.js +85 -0
  97. package/lib/dependencies/CssImportDependency.js +75 -0
  98. package/lib/dependencies/CssLocalIdentifierDependency.js +119 -0
  99. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +101 -0
  100. package/lib/dependencies/CssUrlDependency.js +132 -0
  101. package/lib/dependencies/ExportsInfoDependency.js +6 -0
  102. package/lib/dependencies/HarmonyAcceptImportDependency.js +5 -3
  103. package/lib/dependencies/HarmonyCompatibilityDependency.js +5 -5
  104. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +127 -0
  105. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +12 -3
  106. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +25 -17
  107. package/lib/dependencies/HarmonyExportInitFragment.js +4 -1
  108. package/lib/dependencies/HarmonyImportDependency.js +23 -0
  109. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +142 -45
  110. package/lib/dependencies/HarmonyImportSpecifierDependency.js +46 -22
  111. package/lib/dependencies/HarmonyModulesPlugin.js +10 -0
  112. package/lib/dependencies/ImportContextDependency.js +0 -2
  113. package/lib/dependencies/ImportMetaContextDependency.js +35 -0
  114. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +252 -0
  115. package/lib/dependencies/ImportMetaContextPlugin.js +59 -0
  116. package/lib/dependencies/ImportMetaPlugin.js +22 -3
  117. package/lib/dependencies/ImportParserPlugin.js +35 -29
  118. package/lib/dependencies/JsonExportsDependency.js +17 -21
  119. package/lib/dependencies/LoaderDependency.js +13 -0
  120. package/lib/dependencies/LoaderImportDependency.js +13 -0
  121. package/lib/dependencies/LoaderPlugin.js +4 -2
  122. package/lib/dependencies/ModuleDependency.js +11 -1
  123. package/lib/dependencies/ProvidedDependency.js +31 -8
  124. package/lib/dependencies/RequireContextDependency.js +0 -16
  125. package/lib/dependencies/RequireEnsureDependency.js +2 -2
  126. package/lib/dependencies/RequireResolveContextDependency.js +2 -2
  127. package/lib/dependencies/RequireResolveDependency.js +2 -1
  128. package/lib/dependencies/URLDependency.js +3 -8
  129. package/lib/dependencies/URLPlugin.js +22 -1
  130. package/lib/dependencies/WorkerPlugin.js +2 -0
  131. package/lib/esm/ModuleChunkFormatPlugin.js +74 -49
  132. package/lib/esm/ModuleChunkLoadingPlugin.js +3 -1
  133. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +25 -9
  134. package/lib/hmr/HotModuleReplacement.runtime.js +29 -14
  135. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +4 -3
  136. package/lib/hmr/LazyCompilationPlugin.js +54 -26
  137. package/lib/hmr/lazyCompilationBackend.js +51 -12
  138. package/lib/ids/DeterministicModuleIdsPlugin.js +55 -35
  139. package/lib/ids/HashedModuleIdsPlugin.js +11 -14
  140. package/lib/ids/IdHelpers.js +26 -12
  141. package/lib/ids/NamedModuleIdsPlugin.js +6 -9
  142. package/lib/ids/NaturalModuleIdsPlugin.js +10 -13
  143. package/lib/ids/OccurrenceModuleIdsPlugin.js +13 -10
  144. package/lib/ids/SyncModuleIdsPlugin.js +140 -0
  145. package/lib/index.js +20 -0
  146. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +2 -2
  147. package/lib/javascript/BasicEvaluatedExpression.js +5 -2
  148. package/lib/javascript/ChunkHelpers.js +33 -0
  149. package/lib/javascript/JavascriptGenerator.js +1 -0
  150. package/lib/javascript/JavascriptModulesPlugin.js +27 -2
  151. package/lib/javascript/JavascriptParser.js +143 -73
  152. package/lib/javascript/StartupHelpers.js +7 -30
  153. package/lib/json/JsonData.js +8 -0
  154. package/lib/json/JsonParser.js +4 -6
  155. package/lib/library/AssignLibraryPlugin.js +39 -15
  156. package/lib/library/EnableLibraryPlugin.js +11 -0
  157. package/lib/library/UmdLibraryPlugin.js +5 -3
  158. package/lib/node/NodeTargetPlugin.js +3 -0
  159. package/lib/node/NodeWatchFileSystem.js +85 -31
  160. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +23 -8
  161. package/lib/node/RequireChunkLoadingRuntimeModule.js +24 -9
  162. package/lib/optimize/ConcatenatedModule.js +62 -26
  163. package/lib/optimize/ModuleConcatenationPlugin.js +26 -4
  164. package/lib/optimize/RealContentHashPlugin.js +45 -15
  165. package/lib/optimize/SplitChunksPlugin.js +8 -1
  166. package/lib/runtime/AsyncModuleRuntimeModule.js +50 -66
  167. package/lib/runtime/BaseUriRuntimeModule.js +31 -0
  168. package/lib/runtime/CreateScriptRuntimeModule.js +36 -0
  169. package/lib/runtime/CreateScriptUrlRuntimeModule.js +9 -34
  170. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +76 -0
  171. package/lib/runtime/LoadScriptRuntimeModule.js +11 -9
  172. package/lib/runtime/NonceRuntimeModule.js +24 -0
  173. package/lib/schemes/HttpUriPlugin.js +77 -14
  174. package/lib/serialization/FileMiddleware.js +44 -9
  175. package/lib/sharing/ConsumeSharedModule.js +8 -2
  176. package/lib/sharing/ConsumeSharedRuntimeModule.js +26 -5
  177. package/lib/sharing/ProvideSharedModule.js +4 -2
  178. package/lib/sharing/ProvideSharedPlugin.js +1 -2
  179. package/lib/sharing/ShareRuntimeModule.js +1 -1
  180. package/lib/sharing/utils.js +1 -1
  181. package/lib/stats/DefaultStatsFactoryPlugin.js +113 -68
  182. package/lib/stats/DefaultStatsPrinterPlugin.js +90 -25
  183. package/lib/util/ArrayHelpers.js +30 -0
  184. package/lib/util/AsyncQueue.js +1 -1
  185. package/lib/util/compileBooleanMatcher.js +1 -1
  186. package/lib/util/create-schema-validation.js +9 -2
  187. package/lib/util/createHash.js +12 -0
  188. package/lib/util/deprecation.js +10 -2
  189. package/lib/util/deterministicGrouping.js +1 -1
  190. package/lib/util/extractUrlAndGlobal.js +3 -0
  191. package/lib/util/fs.js +11 -0
  192. package/lib/util/hash/BatchedHash.js +7 -4
  193. package/lib/util/hash/md4.js +20 -0
  194. package/lib/util/hash/wasm-hash.js +163 -0
  195. package/lib/util/hash/xxhash64.js +5 -139
  196. package/lib/util/identifier.js +65 -44
  197. package/lib/util/internalSerializables.js +15 -0
  198. package/lib/util/nonNumericOnlyHash.js +22 -0
  199. package/lib/util/semver.js +17 -10
  200. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +9 -3
  201. package/lib/wasm-sync/WebAssemblyParser.js +1 -1
  202. package/lib/web/JsonpChunkLoadingRuntimeModule.js +31 -18
  203. package/lib/webpack.js +10 -3
  204. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -11
  205. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +33 -22
  206. package/module.d.ts +215 -0
  207. package/package.json +28 -32
  208. package/schemas/WebpackOptions.check.js +1 -1
  209. package/schemas/WebpackOptions.json +321 -30
  210. package/schemas/plugins/BannerPlugin.check.js +1 -1
  211. package/schemas/plugins/BannerPlugin.json +4 -0
  212. package/schemas/plugins/DllReferencePlugin.check.js +1 -1
  213. package/schemas/plugins/HashedModuleIdsPlugin.check.js +1 -1
  214. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  215. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  216. package/schemas/plugins/asset/AssetParserOptions.check.js +1 -1
  217. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  218. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  219. package/schemas/plugins/container/ContainerPlugin.json +2 -1
  220. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  221. package/schemas/plugins/container/ContainerReferencePlugin.json +1 -0
  222. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  223. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  224. package/schemas/plugins/container/ModuleFederationPlugin.json +3 -1
  225. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +7 -0
  226. package/schemas/plugins/css/CssGeneratorOptions.check.js +6 -0
  227. package/schemas/plugins/css/CssGeneratorOptions.json +3 -0
  228. package/schemas/plugins/css/CssParserOptions.check.d.ts +7 -0
  229. package/schemas/plugins/css/CssParserOptions.check.js +6 -0
  230. package/schemas/plugins/css/CssParserOptions.json +3 -0
  231. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js +1 -1
  232. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.js +1 -1
  233. package/schemas/plugins/optimize/MinChunkSizePlugin.check.js +1 -1
  234. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -1
  235. package/schemas/plugins/schemes/HttpUriPlugin.json +4 -0
  236. package/types.d.ts +869 -296
@@ -21,7 +21,7 @@ const HarmonyImportDependency = require("../dependencies/HarmonyImportDependency
21
21
  const JavascriptParser = require("../javascript/JavascriptParser");
22
22
  const { equals } = require("../util/ArrayHelpers");
23
23
  const LazySet = require("../util/LazySet");
24
- const { concatComparators, keepOriginalOrder } = require("../util/comparators");
24
+ const { concatComparators } = require("../util/comparators");
25
25
  const createHash = require("../util/createHash");
26
26
  const { makePathsRelative } = require("../util/identifier");
27
27
  const makeSerializable = require("../util/makeSerializable");
@@ -39,6 +39,7 @@ const {
39
39
  /** @typedef {import("webpack-sources").Source} Source */
40
40
  /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
41
41
  /** @typedef {import("../ChunkGraph")} ChunkGraph */
42
+ /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
42
43
  /** @typedef {import("../Compilation")} Compilation */
43
44
  /** @typedef {import("../Dependency")} Dependency */
44
45
  /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
@@ -184,23 +185,25 @@ const RESERVED_NAMES = new Set(
184
185
  .split(",")
185
186
  );
186
187
 
187
- const bySourceOrder = (a, b) => {
188
- const aOrder = a.sourceOrder;
189
- const bOrder = b.sourceOrder;
190
- if (isNaN(aOrder)) {
191
- if (!isNaN(bOrder)) {
188
+ const createComparator = (property, comparator) => (a, b) =>
189
+ comparator(a[property], b[property]);
190
+ const compareNumbers = (a, b) => {
191
+ if (isNaN(a)) {
192
+ if (!isNaN(b)) {
192
193
  return 1;
193
194
  }
194
195
  } else {
195
- if (isNaN(bOrder)) {
196
+ if (isNaN(b)) {
196
197
  return -1;
197
198
  }
198
- if (aOrder !== bOrder) {
199
- return aOrder < bOrder ? -1 : 1;
199
+ if (a !== b) {
200
+ return a < b ? -1 : 1;
200
201
  }
201
202
  }
202
203
  return 0;
203
204
  };
205
+ const bySourceOrder = createComparator("sourceOrder", compareNumbers);
206
+ const byRangeStart = createComparator("rangeStart", compareNumbers);
204
207
 
205
208
  const joinIterableWithComma = iterable => {
206
209
  // This is more performant than Array.from().join(", ")
@@ -821,10 +824,6 @@ class ConcatenatedModule extends Module {
821
824
  const topLevelDeclarations = this.buildInfo.topLevelDeclarations;
822
825
  if (topLevelDeclarations !== undefined) {
823
826
  for (const decl of m.buildInfo.topLevelDeclarations) {
824
- // reserved names will always be renamed
825
- if (RESERVED_NAMES.has(decl)) continue;
826
- // TODO actually this is incorrect since with renaming there could be more
827
- // We should do the renaming during build
828
827
  topLevelDeclarations.add(decl);
829
828
  }
830
829
  }
@@ -888,6 +887,9 @@ class ConcatenatedModule extends Module {
888
887
  for (const c of moduleGraph.getOutgoingConnections(this))
889
888
  connections.push(c);
890
889
  }
890
+ /**
891
+ * @type {Array<{ connection: ModuleGraphConnection, sourceOrder: number, rangeStart: number }>}
892
+ */
891
893
  const references = connections
892
894
  .filter(connection => {
893
895
  if (!(connection.dependency instanceof HarmonyImportDependency))
@@ -899,15 +901,33 @@ class ConcatenatedModule extends Module {
899
901
  connection.isTargetActive(runtime)
900
902
  );
901
903
  })
902
- .map(connection => ({
903
- connection,
904
- sourceOrder: /** @type {HarmonyImportDependency} */ (
904
+ .map(connection => {
905
+ const dep = /** @type {HarmonyImportDependency} */ (
905
906
  connection.dependency
906
- ).sourceOrder
907
- }));
908
- references.sort(
909
- concatComparators(bySourceOrder, keepOriginalOrder(references))
910
- );
907
+ );
908
+ return {
909
+ connection,
910
+ sourceOrder: dep.sourceOrder,
911
+ rangeStart: dep.range && dep.range[0]
912
+ };
913
+ });
914
+ /**
915
+ * bySourceOrder
916
+ * @example
917
+ * import a from "a"; // sourceOrder=1
918
+ * import b from "b"; // sourceOrder=2
919
+ *
920
+ * byRangeStart
921
+ * @example
922
+ * import {a, b} from "a"; // sourceOrder=1
923
+ * a.a(); // first range
924
+ * b.b(); // second range
925
+ *
926
+ * If there is no reexport, we have the same source.
927
+ * If there is reexport, but module has side effects, this will lead to reexport module only.
928
+ * If there is side-effects-free reexport, we can get simple deterministic result with range start comparison.
929
+ */
930
+ references.sort(concatComparators(bySourceOrder, byRangeStart));
911
931
  /** @type {Map<Module, { connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} */
912
932
  const referencesMap = new Map();
913
933
  for (const { connection } of references) {
@@ -1077,7 +1097,8 @@ class ConcatenatedModule extends Module {
1077
1097
  runtimeTemplate,
1078
1098
  moduleGraph,
1079
1099
  chunkGraph,
1080
- runtime: generationRuntime
1100
+ runtime: generationRuntime,
1101
+ codeGenerationResults
1081
1102
  }) {
1082
1103
  /** @type {Set<string>} */
1083
1104
  const runtimeRequirements = new Set();
@@ -1104,12 +1125,15 @@ class ConcatenatedModule extends Module {
1104
1125
  runtimeTemplate,
1105
1126
  moduleGraph,
1106
1127
  chunkGraph,
1107
- runtime
1128
+ runtime,
1129
+ codeGenerationResults
1108
1130
  );
1109
1131
  }
1110
1132
 
1111
1133
  // List of all used names to avoid conflicts
1112
1134
  const allUsedNames = new Set(RESERVED_NAMES);
1135
+ // Updated Top level declarations are created by renaming
1136
+ const topLevelDeclarations = new Set();
1113
1137
 
1114
1138
  // List of additional names in scope for module references
1115
1139
  /** @type {Map<string, { usedNames: Set<string>, alreadyCheckedScopes: Set<TODO> }>} */
@@ -1254,6 +1278,7 @@ class ConcatenatedModule extends Module {
1254
1278
  );
1255
1279
  allUsedNames.add(newName);
1256
1280
  info.internalNames.set(name, newName);
1281
+ topLevelDeclarations.add(newName);
1257
1282
  const source = info.source;
1258
1283
  const allIdentifiers = new Set(
1259
1284
  references.map(r => r.identifier).concat(variable.identifiers)
@@ -1280,6 +1305,7 @@ class ConcatenatedModule extends Module {
1280
1305
  } else {
1281
1306
  allUsedNames.add(name);
1282
1307
  info.internalNames.set(name, name);
1308
+ topLevelDeclarations.add(name);
1283
1309
  }
1284
1310
  }
1285
1311
  let namespaceObjectName;
@@ -1297,6 +1323,7 @@ class ConcatenatedModule extends Module {
1297
1323
  allUsedNames.add(namespaceObjectName);
1298
1324
  }
1299
1325
  info.namespaceObjectName = namespaceObjectName;
1326
+ topLevelDeclarations.add(namespaceObjectName);
1300
1327
  break;
1301
1328
  }
1302
1329
  case "external": {
@@ -1308,6 +1335,7 @@ class ConcatenatedModule extends Module {
1308
1335
  );
1309
1336
  allUsedNames.add(externalName);
1310
1337
  info.name = externalName;
1338
+ topLevelDeclarations.add(externalName);
1311
1339
  break;
1312
1340
  }
1313
1341
  }
@@ -1320,6 +1348,7 @@ class ConcatenatedModule extends Module {
1320
1348
  );
1321
1349
  allUsedNames.add(externalNameInterop);
1322
1350
  info.interopNamespaceObjectName = externalNameInterop;
1351
+ topLevelDeclarations.add(externalNameInterop);
1323
1352
  }
1324
1353
  if (
1325
1354
  info.module.buildMeta.exportsType === "default" &&
@@ -1333,6 +1362,7 @@ class ConcatenatedModule extends Module {
1333
1362
  );
1334
1363
  allUsedNames.add(externalNameInterop);
1335
1364
  info.interopNamespaceObject2Name = externalNameInterop;
1365
+ topLevelDeclarations.add(externalNameInterop);
1336
1366
  }
1337
1367
  if (
1338
1368
  info.module.buildMeta.exportsType === "dynamic" ||
@@ -1346,6 +1376,7 @@ class ConcatenatedModule extends Module {
1346
1376
  );
1347
1377
  allUsedNames.add(externalNameInterop);
1348
1378
  info.interopDefaultAccessName = externalNameInterop;
1379
+ topLevelDeclarations.add(externalNameInterop);
1349
1380
  }
1350
1381
  }
1351
1382
 
@@ -1615,6 +1646,7 @@ ${defineGetters}`
1615
1646
  const data = new Map();
1616
1647
  if (chunkInitFragments.length > 0)
1617
1648
  data.set("chunkInitFragments", chunkInitFragments);
1649
+ data.set("topLevelDeclarations", topLevelDeclarations);
1618
1650
 
1619
1651
  /** @type {CodeGenerationResult} */
1620
1652
  const resultEntry = {
@@ -1634,6 +1666,7 @@ ${defineGetters}`
1634
1666
  * @param {ModuleGraph} moduleGraph moduleGraph
1635
1667
  * @param {ChunkGraph} chunkGraph chunkGraph
1636
1668
  * @param {RuntimeSpec} runtime runtime
1669
+ * @param {CodeGenerationResults} codeGenerationResults codeGenerationResults
1637
1670
  */
1638
1671
  _analyseModule(
1639
1672
  modulesMap,
@@ -1642,7 +1675,8 @@ ${defineGetters}`
1642
1675
  runtimeTemplate,
1643
1676
  moduleGraph,
1644
1677
  chunkGraph,
1645
- runtime
1678
+ runtime,
1679
+ codeGenerationResults
1646
1680
  ) {
1647
1681
  if (info.type === "concatenated") {
1648
1682
  const m = info.module;
@@ -1657,7 +1691,9 @@ ${defineGetters}`
1657
1691
  moduleGraph,
1658
1692
  chunkGraph,
1659
1693
  runtime,
1660
- concatenationScope
1694
+ concatenationScope,
1695
+ codeGenerationResults,
1696
+ sourceTypes: TYPES
1661
1697
  });
1662
1698
  const source = codeGenResult.sources.get("javascript");
1663
1699
  const data = codeGenResult.data;
@@ -1702,7 +1738,7 @@ ${defineGetters}`
1702
1738
  info.globalScope = globalScope;
1703
1739
  info.moduleScope = moduleScope;
1704
1740
  } catch (err) {
1705
- err.message += `\nwhile analysing module ${m.identifier()} for concatenation`;
1741
+ err.message += `\nwhile analyzing module ${m.identifier()} for concatenation`;
1706
1742
  throw err;
1707
1743
  }
1708
1744
  }
@@ -56,7 +56,13 @@ class ModuleConcatenationPlugin {
56
56
  * @returns {void}
57
57
  */
58
58
  apply(compiler) {
59
+ const { _backCompat: backCompat } = compiler;
59
60
  compiler.hooks.compilation.tap("ModuleConcatenationPlugin", compilation => {
61
+ if (compilation.moduleMemCaches) {
62
+ throw new Error(
63
+ "optimization.concatenateModules can't be used with cacheUnaffected as module concatenation is a global effect"
64
+ );
65
+ }
60
66
  const moduleGraph = compilation.moduleGraph;
61
67
  const bailoutReasonMap = new Map();
62
68
 
@@ -389,8 +395,10 @@ class ModuleConcatenationPlugin {
389
395
  };
390
396
 
391
397
  const integrate = () => {
392
- ChunkGraph.setChunkGraphForModule(newModule, chunkGraph);
393
- ModuleGraph.setModuleGraphForModule(newModule, moduleGraph);
398
+ if (backCompat) {
399
+ ChunkGraph.setChunkGraphForModule(newModule, chunkGraph);
400
+ ModuleGraph.setModuleGraphForModule(newModule, moduleGraph);
401
+ }
394
402
 
395
403
  for (const warning of concatConfiguration.getWarningsSorted()) {
396
404
  moduleGraph
@@ -422,7 +430,21 @@ class ModuleConcatenationPlugin {
422
430
  for (const chunk of chunkGraph.getModuleChunksIterable(
423
431
  rootModule
424
432
  )) {
425
- chunkGraph.disconnectChunkAndModule(chunk, m);
433
+ const sourceTypes = chunkGraph.getChunkModuleSourceTypes(
434
+ chunk,
435
+ m
436
+ );
437
+ if (sourceTypes.size === 1) {
438
+ chunkGraph.disconnectChunkAndModule(chunk, m);
439
+ } else {
440
+ const newSourceTypes = new Set(sourceTypes);
441
+ newSourceTypes.delete("javascript");
442
+ chunkGraph.setChunkModuleSourceTypes(
443
+ chunk,
444
+ m,
445
+ newSourceTypes
446
+ );
447
+ }
426
448
  }
427
449
  }
428
450
  }
@@ -584,7 +606,7 @@ class ModuleConcatenationPlugin {
584
606
  incomingConnectionsFromNonModules.filter(connection => {
585
607
  // We are not interested in inactive connections
586
608
  // or connections without dependency
587
- return connection.isActive(runtime) || connection.dependency;
609
+ return connection.isActive(runtime);
588
610
  });
589
611
  if (activeNonModulesConnections.length > 0) {
590
612
  const problem = requestShortener => {
@@ -178,10 +178,43 @@ class RealContentHashPlugin {
178
178
  }
179
179
  }
180
180
  if (hashToAssets.size === 0) return;
181
- const hashRegExp = new RegExp(
182
- Array.from(hashToAssets.keys(), quoteMeta).join("|"),
183
- "g"
181
+ const hashRegExps = Array.from(hashToAssets.keys(), quoteMeta).map(
182
+ hash => new RegExp(hash, "g")
184
183
  );
184
+
185
+ /**
186
+ * @param {string} str string to be matched against all hashRegExps
187
+ * @returns {string[] | null} matches found
188
+ */
189
+ const hashMatch = str => {
190
+ /** @type {string[]} */
191
+ const results = [];
192
+ for (const hashRegExp of hashRegExps) {
193
+ const matches = str.match(hashRegExp);
194
+ if (matches) {
195
+ matches.forEach(match => results.push(match));
196
+ }
197
+ }
198
+ if (results.length) {
199
+ return results;
200
+ } else {
201
+ return null;
202
+ }
203
+ };
204
+
205
+ /**
206
+ * @param {string} str string to be replaced with all hashRegExps
207
+ * @param {function(string): string} fn replacement function to use when a hash is found
208
+ * @returns {string} replaced content
209
+ */
210
+ const hashReplace = (str, fn) => {
211
+ let result = str;
212
+ for (const hashRegExp of hashRegExps) {
213
+ result = result.replace(hashRegExp, fn);
214
+ }
215
+ return result;
216
+ };
217
+
185
218
  await Promise.all(
186
219
  assetsWithInfo.map(async asset => {
187
220
  const { name, source, content, hashes } = asset;
@@ -198,7 +231,7 @@ class RealContentHashPlugin {
198
231
  await cacheAnalyse.providePromise(name, etag, () => {
199
232
  const referencedHashes = new Set();
200
233
  let ownHashes = new Set();
201
- const inContent = content.match(hashRegExp);
234
+ const inContent = hashMatch(content);
202
235
  if (inContent) {
203
236
  for (const hash of inContent) {
204
237
  if (hashes.has(hash)) {
@@ -298,7 +331,7 @@ ${referencingAssets
298
331
  identifier,
299
332
  etag,
300
333
  () => {
301
- const newContent = asset.content.replace(hashRegExp, hash =>
334
+ const newContent = hashReplace(asset.content, hash =>
302
335
  hashToNewHash.get(hash)
303
336
  );
304
337
  return new RawSource(newContent);
@@ -323,15 +356,12 @@ ${referencingAssets
323
356
  identifier,
324
357
  etag,
325
358
  () => {
326
- const newContent = asset.content.replace(
327
- hashRegExp,
328
- hash => {
329
- if (asset.ownHashes.has(hash)) {
330
- return "";
331
- }
332
- return hashToNewHash.get(hash);
359
+ const newContent = hashReplace(asset.content, hash => {
360
+ if (asset.ownHashes.has(hash)) {
361
+ return "";
333
362
  }
334
- );
363
+ return hashToNewHash.get(hash);
364
+ });
335
365
  return new RawSource(newContent);
336
366
  }
337
367
  );
@@ -342,7 +372,6 @@ ${referencingAssets
342
372
  for (const oldHash of hashesInOrder) {
343
373
  const assets = hashToAssets.get(oldHash);
344
374
  assets.sort(comparator);
345
- const hash = createHash(this._hashFunction);
346
375
  await Promise.all(
347
376
  assets.map(asset =>
348
377
  asset.ownHashes.has(oldHash)
@@ -363,6 +392,7 @@ ${referencingAssets
363
392
  });
364
393
  let newHash = hooks.updateHash.call(assetsContent, oldHash);
365
394
  if (!newHash) {
395
+ const hash = createHash(this._hashFunction);
366
396
  for (const content of assetsContent) {
367
397
  hash.update(content);
368
398
  }
@@ -374,7 +404,7 @@ ${referencingAssets
374
404
  await Promise.all(
375
405
  assetsWithInfo.map(async asset => {
376
406
  await computeNewContent(asset);
377
- const newName = asset.name.replace(hashRegExp, hash =>
407
+ const newName = hashReplace(asset.name, hash =>
378
408
  hashToNewHash.get(hash)
379
409
  );
380
410
 
@@ -102,6 +102,7 @@ const MinMaxSizeWarning = require("./MinMaxSizeWarning");
102
102
 
103
103
  /**
104
104
  * @typedef {Object} FallbackCacheGroup
105
+ * @property {ChunkFilterFunction} chunksFilter
105
106
  * @property {SplitChunksSizes} minSize
106
107
  * @property {SplitChunksSizes} maxAsyncSize
107
108
  * @property {SplitChunksSizes} maxInitialSize
@@ -658,6 +659,9 @@ module.exports = class SplitChunksPlugin {
658
659
  automaticNameDelimiter: options.automaticNameDelimiter,
659
660
  usedExports: options.usedExports,
660
661
  fallbackCacheGroup: {
662
+ chunksFilter: normalizeChunksFilter(
663
+ fallbackCacheGroup.chunks || options.chunks || "all"
664
+ ),
661
665
  minSize: mergeSizes(
662
666
  normalizeSizes(fallbackCacheGroup.minSize, defaultSizeTypes),
663
667
  minSize
@@ -1598,6 +1602,7 @@ module.exports = class SplitChunksPlugin {
1598
1602
  const { outputOptions } = compilation;
1599
1603
 
1600
1604
  // Make sure that maxSize is fulfilled
1605
+ const { fallbackCacheGroup } = this.options;
1601
1606
  for (const chunk of Array.from(compilation.chunks)) {
1602
1607
  const chunkConfig = maxSizeQueueMap.get(chunk);
1603
1608
  const {
@@ -1605,7 +1610,9 @@ module.exports = class SplitChunksPlugin {
1605
1610
  maxAsyncSize,
1606
1611
  maxInitialSize,
1607
1612
  automaticNameDelimiter
1608
- } = chunkConfig || this.options.fallbackCacheGroup;
1613
+ } = chunkConfig || fallbackCacheGroup;
1614
+ if (!chunkConfig && !fallbackCacheGroup.chunksFilter(chunk))
1615
+ continue;
1609
1616
  /** @type {SplitChunksSizes} */
1610
1617
  let maxSize;
1611
1618
  if (chunk.isOnlyInitial()) {
@@ -20,11 +20,13 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
20
20
  const { runtimeTemplate } = this.compilation;
21
21
  const fn = RuntimeGlobals.asyncModule;
22
22
  return Template.asString([
23
- 'var webpackThen = typeof Symbol === "function" ? Symbol("webpack then") : "__webpack_then__";',
23
+ 'var webpackQueues = typeof Symbol === "function" ? Symbol("webpack queues") : "__webpack_queues__";',
24
24
  'var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";',
25
- `var completeQueue = ${runtimeTemplate.basicFunction("queue", [
26
- "if(queue) {",
25
+ 'var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__";',
26
+ `var resolveQueue = ${runtimeTemplate.basicFunction("queue", [
27
+ "if(queue && !queue.d) {",
27
28
  Template.indent([
29
+ "queue.d = 1;",
28
30
  `queue.forEach(${runtimeTemplate.expressionFunction(
29
31
  "fn.r--",
30
32
  "fn"
@@ -36,108 +38,90 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
36
38
  ]),
37
39
  "}"
38
40
  ])}`,
39
- `var completeFunction = ${runtimeTemplate.expressionFunction(
40
- "!--fn.r && fn()",
41
- "fn"
42
- )};`,
43
- `var queueFunction = ${runtimeTemplate.expressionFunction(
44
- "queue ? queue.push(fn) : completeFunction(fn)",
45
- "queue, fn"
46
- )};`,
47
41
  `var wrapDeps = ${runtimeTemplate.returningFunction(
48
42
  `deps.map(${runtimeTemplate.basicFunction("dep", [
49
43
  'if(dep !== null && typeof dep === "object") {',
50
44
  Template.indent([
51
- "if(dep[webpackThen]) return dep;",
45
+ "if(dep[webpackQueues]) return dep;",
52
46
  "if(dep.then) {",
53
47
  Template.indent([
54
48
  "var queue = [];",
49
+ "queue.d = 0;",
55
50
  `dep.then(${runtimeTemplate.basicFunction("r", [
56
51
  "obj[webpackExports] = r;",
57
- "completeQueue(queue);",
58
- "queue = 0;"
52
+ "resolveQueue(queue);"
53
+ ])}, ${runtimeTemplate.basicFunction("e", [
54
+ "obj[webpackError] = e;",
55
+ "resolveQueue(queue);"
59
56
  ])});`,
60
- `var obj = {};
61
- obj[webpackThen] = ${runtimeTemplate.expressionFunction(
62
- "queueFunction(queue, fn), dep.catch(reject)",
63
- "fn, reject"
57
+ "var obj = {};",
58
+ `obj[webpackQueues] = ${runtimeTemplate.expressionFunction(
59
+ `fn(queue)`,
60
+ "fn"
64
61
  )};`,
65
62
  "return obj;"
66
63
  ]),
67
64
  "}"
68
65
  ]),
69
66
  "}",
70
- `var ret = {};
71
- ret[webpackThen] = ${runtimeTemplate.expressionFunction(
72
- "completeFunction(fn)",
73
- "fn"
74
- )};
75
- ret[webpackExports] = dep;
76
- return ret;`
67
+ "var ret = {};",
68
+ `ret[webpackQueues] = ${runtimeTemplate.emptyFunction()};`,
69
+ "ret[webpackExports] = dep;",
70
+ "return ret;"
77
71
  ])})`,
78
72
  "deps"
79
73
  )};`,
80
74
  `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [
81
- "var queue = hasAwait && [];",
75
+ "var queue;",
76
+ "hasAwait && ((queue = []).d = 1);",
77
+ "var depQueues = new Set();",
82
78
  "var exports = module.exports;",
83
79
  "var currentDeps;",
84
80
  "var outerResolve;",
85
81
  "var reject;",
86
- "var isEvaluating = true;",
87
- "var nested = false;",
88
- `var whenAll = ${runtimeTemplate.basicFunction(
89
- "deps, onResolve, onReject",
90
- [
91
- "if (nested) return;",
92
- "nested = true;",
93
- "onResolve.r += deps.length;",
94
- `deps.map(${runtimeTemplate.expressionFunction(
95
- "dep[webpackThen](onResolve, onReject)",
96
- "dep, i"
97
- )});`,
98
- "nested = false;"
99
- ]
100
- )};`,
101
82
  `var promise = new Promise(${runtimeTemplate.basicFunction(
102
83
  "resolve, rej",
103
- [
104
- "reject = rej;",
105
- `outerResolve = ${runtimeTemplate.expressionFunction(
106
- "resolve(exports), completeQueue(queue), queue = 0"
107
- )};`
108
- ]
84
+ ["reject = rej;", "outerResolve = resolve;"]
109
85
  )});`,
110
86
  "promise[webpackExports] = exports;",
111
- `promise[webpackThen] = ${runtimeTemplate.basicFunction(
112
- "fn, rejectFn",
113
- [
114
- "if (isEvaluating) { return completeFunction(fn); }",
115
- "if (currentDeps) whenAll(currentDeps, fn, rejectFn);",
116
- "queueFunction(queue, fn);",
117
- "promise.catch(rejectFn);"
118
- ]
87
+ `promise[webpackQueues] = ${runtimeTemplate.expressionFunction(
88
+ `queue && fn(queue), depQueues.forEach(fn), promise["catch"](${runtimeTemplate.emptyFunction()})`,
89
+ "fn"
119
90
  )};`,
120
91
  "module.exports = promise;",
121
92
  `body(${runtimeTemplate.basicFunction("deps", [
122
- "if(!deps) return outerResolve();",
123
93
  "currentDeps = wrapDeps(deps);",
124
- "var fn, result;",
94
+ "var fn;",
95
+ `var getResult = ${runtimeTemplate.returningFunction(
96
+ `currentDeps.map(${runtimeTemplate.basicFunction("d", [
97
+ "if(d[webpackError]) throw d[webpackError];",
98
+ "return d[webpackExports];"
99
+ ])})`
100
+ )}`,
125
101
  `var promise = new Promise(${runtimeTemplate.basicFunction(
126
- "resolve, reject",
102
+ "resolve",
127
103
  [
128
104
  `fn = ${runtimeTemplate.expressionFunction(
129
- `resolve(result = currentDeps.map(${runtimeTemplate.returningFunction(
130
- "d[webpackExports]",
131
- "d"
132
- )}))`
105
+ "resolve(getResult)",
106
+ ""
133
107
  )};`,
134
108
  "fn.r = 0;",
135
- "whenAll(currentDeps, fn, reject);"
109
+ `var fnQueue = ${runtimeTemplate.expressionFunction(
110
+ "q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn)))",
111
+ "q"
112
+ )};`,
113
+ `currentDeps.map(${runtimeTemplate.expressionFunction(
114
+ "dep[webpackQueues](fnQueue)",
115
+ "dep"
116
+ )});`
136
117
  ]
137
118
  )});`,
138
- "return fn.r ? promise : result;"
139
- ])}).then(outerResolve, reject);`,
140
- "isEvaluating = false;"
119
+ "return fn.r ? promise : getResult();"
120
+ ])}, ${runtimeTemplate.expressionFunction(
121
+ "(err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)",
122
+ "err"
123
+ )});`,
124
+ "queue && (queue.d = 0);"
141
125
  ])};`
142
126
  ]);
143
127
  }
@@ -0,0 +1,31 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Ivan Kopeykin @vankop
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const RuntimeGlobals = require("../RuntimeGlobals");
9
+ const RuntimeModule = require("../RuntimeModule");
10
+
11
+ class BaseUriRuntimeModule extends RuntimeModule {
12
+ constructor() {
13
+ super("base uri", RuntimeModule.STAGE_ATTACH);
14
+ }
15
+
16
+ /**
17
+ * @returns {string} runtime code
18
+ */
19
+ generate() {
20
+ const { chunk } = this;
21
+
22
+ const options = chunk.getEntryOptions();
23
+ return `${RuntimeGlobals.baseURI} = ${
24
+ options.baseUri === undefined
25
+ ? "undefined"
26
+ : JSON.stringify(options.baseUri)
27
+ };`;
28
+ }
29
+ }
30
+
31
+ module.exports = BaseUriRuntimeModule;
@@ -0,0 +1,36 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ */
4
+
5
+ "use strict";
6
+
7
+ const RuntimeGlobals = require("../RuntimeGlobals");
8
+ const Template = require("../Template");
9
+ const HelperRuntimeModule = require("./HelperRuntimeModule");
10
+
11
+ class CreateScriptRuntimeModule extends HelperRuntimeModule {
12
+ constructor() {
13
+ super("trusted types script");
14
+ }
15
+
16
+ /**
17
+ * @returns {string} runtime code
18
+ */
19
+ generate() {
20
+ const { compilation } = this;
21
+ const { runtimeTemplate, outputOptions } = compilation;
22
+ const { trustedTypes } = outputOptions;
23
+ const fn = RuntimeGlobals.createScript;
24
+
25
+ return Template.asString(
26
+ `${fn} = ${runtimeTemplate.returningFunction(
27
+ trustedTypes
28
+ ? `${RuntimeGlobals.getTrustedTypesPolicy}().createScript(script)`
29
+ : "script",
30
+ "script"
31
+ )};`
32
+ );
33
+ }
34
+ }
35
+
36
+ module.exports = CreateScriptRuntimeModule;