webpack 5.94.0 → 5.96.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 (151) hide show
  1. package/README.md +1 -1
  2. package/lib/AsyncDependenciesBlock.js +1 -1
  3. package/lib/BannerPlugin.js +2 -1
  4. package/lib/Chunk.js +30 -0
  5. package/lib/ChunkGraph.js +11 -6
  6. package/lib/ChunkGroup.js +2 -2
  7. package/lib/CleanPlugin.js +4 -5
  8. package/lib/CodeGenerationResults.js +6 -5
  9. package/lib/Compilation.js +71 -48
  10. package/lib/Compiler.js +7 -5
  11. package/lib/ConcatenationScope.js +7 -20
  12. package/lib/ContextModule.js +7 -8
  13. package/lib/CssModule.js +25 -21
  14. package/lib/DefinePlugin.js +14 -8
  15. package/lib/DelegatedModule.js +3 -3
  16. package/lib/DllModule.js +4 -4
  17. package/lib/DynamicEntryPlugin.js +29 -22
  18. package/lib/EnvironmentPlugin.js +3 -2
  19. package/lib/EvalDevToolModulePlugin.js +5 -2
  20. package/lib/EvalSourceMapDevToolPlugin.js +5 -2
  21. package/lib/ExternalModule.js +118 -99
  22. package/lib/ExternalModuleFactoryPlugin.js +33 -9
  23. package/lib/FileSystemInfo.js +12 -8
  24. package/lib/Generator.js +5 -4
  25. package/lib/HotModuleReplacementPlugin.js +8 -6
  26. package/lib/IgnorePlugin.js +19 -1
  27. package/lib/LoaderOptionsPlugin.js +3 -1
  28. package/lib/Module.js +9 -8
  29. package/lib/ModuleSourceTypesConstants.js +100 -0
  30. package/lib/NormalModule.js +27 -13
  31. package/lib/NormalModuleFactory.js +38 -22
  32. package/lib/OptionsApply.js +12 -1
  33. package/lib/ProgressPlugin.js +50 -10
  34. package/lib/RawModule.js +3 -4
  35. package/lib/RuntimeModule.js +3 -4
  36. package/lib/RuntimePlugin.js +11 -4
  37. package/lib/RuntimeTemplate.js +13 -42
  38. package/lib/SourceMapDevToolPlugin.js +10 -7
  39. package/lib/TemplatedPathPlugin.js +9 -3
  40. package/lib/Watching.js +2 -2
  41. package/lib/WebpackOptionsApply.js +42 -21
  42. package/lib/asset/AssetGenerator.js +347 -194
  43. package/lib/asset/AssetModulesPlugin.js +2 -1
  44. package/lib/asset/AssetSourceGenerator.js +82 -27
  45. package/lib/asset/RawDataUrlModule.js +5 -4
  46. package/lib/buildChunkGraph.js +79 -62
  47. package/lib/cache/PackFileCacheStrategy.js +69 -31
  48. package/lib/cache/ResolverCachePlugin.js +248 -173
  49. package/lib/config/defaults.js +135 -126
  50. package/lib/container/ContainerEntryModule.js +3 -4
  51. package/lib/container/ContainerPlugin.js +8 -0
  52. package/lib/container/FallbackModule.js +2 -2
  53. package/lib/container/HoistContainerReferencesPlugin.js +250 -0
  54. package/lib/container/ModuleFederationPlugin.js +38 -1
  55. package/lib/container/RemoteModule.js +4 -2
  56. package/lib/container/RemoteRuntimeModule.js +4 -2
  57. package/lib/css/CssExportsGenerator.js +16 -12
  58. package/lib/css/CssGenerator.js +22 -16
  59. package/lib/css/CssLoadingRuntimeModule.js +7 -6
  60. package/lib/css/CssModulesPlugin.js +122 -77
  61. package/lib/css/CssParser.js +655 -526
  62. package/lib/css/walkCssTokens.js +1168 -338
  63. package/lib/debug/ProfilingPlugin.js +5 -0
  64. package/lib/dependencies/CommonJsExportsParserPlugin.js +5 -2
  65. package/lib/dependencies/CommonJsImportsParserPlugin.js +3 -6
  66. package/lib/dependencies/ContextDependency.js +6 -1
  67. package/lib/dependencies/ContextElementDependency.js +33 -6
  68. package/lib/dependencies/CssExportDependency.js +3 -3
  69. package/lib/dependencies/CssLocalIdentifierDependency.js +26 -17
  70. package/lib/dependencies/CssUrlDependency.js +33 -3
  71. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +3 -3
  72. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +39 -14
  73. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +15 -82
  74. package/lib/dependencies/HarmonyImportSpecifierDependency.js +5 -2
  75. package/lib/dependencies/ImportParserPlugin.js +9 -7
  76. package/lib/dependencies/LoaderPlugin.js +19 -0
  77. package/lib/dependencies/SystemPlugin.js +2 -1
  78. package/lib/dependencies/URLPlugin.js +7 -1
  79. package/lib/dependencies/WorkerPlugin.js +1 -1
  80. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +4 -2
  81. package/lib/hmr/HotModuleReplacement.runtime.js +1 -0
  82. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +1 -0
  83. package/lib/hmr/LazyCompilationPlugin.js +16 -4
  84. package/lib/hmr/lazyCompilationBackend.js +1 -7
  85. package/lib/index.js +35 -6
  86. package/lib/javascript/EnableChunkLoadingPlugin.js +2 -2
  87. package/lib/javascript/JavascriptGenerator.js +8 -8
  88. package/lib/javascript/JavascriptModulesPlugin.js +166 -88
  89. package/lib/javascript/JavascriptParser.js +338 -117
  90. package/lib/json/JsonGenerator.js +5 -5
  91. package/lib/library/EnableLibraryPlugin.js +2 -2
  92. package/lib/library/ExportPropertyLibraryPlugin.js +1 -1
  93. package/lib/library/UmdLibraryPlugin.js +16 -8
  94. package/lib/logging/Logger.js +11 -11
  95. package/lib/logging/createConsoleLogger.js +14 -14
  96. package/lib/logging/truncateArgs.js +1 -1
  97. package/lib/node/NodeWatchFileSystem.js +3 -1
  98. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +20 -18
  99. package/lib/node/ReadFileCompileWasmPlugin.js +1 -2
  100. package/lib/node/nodeConsole.js +11 -8
  101. package/lib/optimize/AggressiveSplittingPlugin.js +21 -7
  102. package/lib/optimize/ConcatenatedModule.js +44 -148
  103. package/lib/optimize/FlagIncludedChunksPlugin.js +6 -0
  104. package/lib/optimize/InnerGraphPlugin.js +57 -16
  105. package/lib/optimize/LimitChunkCountPlugin.js +2 -4
  106. package/lib/optimize/MergeDuplicateChunksPlugin.js +2 -2
  107. package/lib/optimize/ModuleConcatenationPlugin.js +4 -2
  108. package/lib/optimize/RealContentHashPlugin.js +1 -1
  109. package/lib/optimize/SideEffectsFlagPlugin.js +6 -3
  110. package/lib/rules/RuleSetCompiler.js +2 -2
  111. package/lib/runtime/GetChunkFilenameRuntimeModule.js +2 -2
  112. package/lib/schemes/DataUriPlugin.js +1 -1
  113. package/lib/serialization/BinaryMiddleware.js +32 -19
  114. package/lib/serialization/ObjectMiddleware.js +23 -9
  115. package/lib/serialization/SerializerMiddleware.js +3 -2
  116. package/lib/serialization/types.js +2 -2
  117. package/lib/sharing/ConsumeSharedModule.js +2 -3
  118. package/lib/sharing/ConsumeSharedRuntimeModule.js +3 -1
  119. package/lib/sharing/ProvideSharedModule.js +2 -3
  120. package/lib/stats/DefaultStatsFactoryPlugin.js +22 -20
  121. package/lib/stats/StatsFactory.js +12 -12
  122. package/lib/stats/StatsPrinter.js +7 -7
  123. package/lib/util/AsyncQueue.js +17 -1
  124. package/lib/util/IterableHelpers.js +1 -1
  125. package/lib/util/LazySet.js +12 -0
  126. package/lib/util/SetHelpers.js +1 -1
  127. package/lib/util/cleverMerge.js +48 -24
  128. package/lib/util/concatenate.js +227 -0
  129. package/lib/util/create-schema-validation.js +22 -9
  130. package/lib/util/deprecation.js +86 -28
  131. package/lib/util/fs.js +10 -10
  132. package/lib/util/hash/wasm-hash.js +12 -1
  133. package/lib/util/magicComment.js +21 -0
  134. package/lib/util/makeSerializable.js +24 -1
  135. package/lib/util/memoize.js +2 -1
  136. package/lib/util/runtime.js +10 -1
  137. package/lib/util/semver.js +130 -23
  138. package/lib/wasm/EnableWasmLoadingPlugin.js +2 -2
  139. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +3 -3
  140. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +5 -5
  141. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +5 -5
  142. package/lib/wasm-sync/WebAssemblyGenerator.js +8 -9
  143. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +5 -5
  144. package/lib/web/FetchCompileAsyncWasmPlugin.js +1 -2
  145. package/lib/web/FetchCompileWasmPlugin.js +1 -2
  146. package/lib/web/JsonpChunkLoadingRuntimeModule.js +6 -6
  147. package/package.json +19 -20
  148. package/schemas/WebpackOptions.check.js +1 -1
  149. package/schemas/WebpackOptions.json +12 -2
  150. package/types.d.ts +817 -269
  151. package/lib/util/mergeScope.js +0 -76
@@ -31,13 +31,21 @@ const Template = require("../Template");
31
31
  const { last, someInIterable } = require("../util/IterableHelpers");
32
32
  const StringXor = require("../util/StringXor");
33
33
  const { compareModulesByIdentifier } = require("../util/comparators");
34
+ const {
35
+ getPathInAst,
36
+ getAllReferences,
37
+ RESERVED_NAMES,
38
+ findNewName,
39
+ addScopeSymbols,
40
+ getUsedNamesInScopeInfo
41
+ } = require("../util/concatenate");
34
42
  const createHash = require("../util/createHash");
35
- const { getPathInAst, getAllReferences } = require("../util/mergeScope");
36
43
  const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
37
44
  const { intersectRuntime } = require("../util/runtime");
38
45
  const JavascriptGenerator = require("./JavascriptGenerator");
39
46
  const JavascriptParser = require("./JavascriptParser");
40
47
 
48
+ /** @typedef {import("eslint-scope").Reference} Reference */
41
49
  /** @typedef {import("eslint-scope").Scope} Scope */
42
50
  /** @typedef {import("eslint-scope").Variable} Variable */
43
51
  /** @typedef {import("webpack-sources").Source} Source */
@@ -46,6 +54,7 @@ const JavascriptParser = require("./JavascriptParser");
46
54
  /** @typedef {import("../ChunkGraph")} ChunkGraph */
47
55
  /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
48
56
  /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
57
+ /** @typedef {import("../Compilation").ModuleObject} ModuleObject */
49
58
  /** @typedef {import("../Compiler")} Compiler */
50
59
  /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
51
60
  /** @typedef {import("../Entrypoint")} Entrypoint */
@@ -54,8 +63,10 @@ const JavascriptParser = require("./JavascriptParser");
54
63
  /** @typedef {import("../ModuleGraph")} ModuleGraph */
55
64
  /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
56
65
  /** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
66
+ /** @typedef {import("../WebpackError")} WebpackError */
57
67
  /** @typedef {import("../javascript/JavascriptParser").Range} Range */
58
68
  /** @typedef {import("../util/Hash")} Hash */
69
+ /** @typedef {import("../util/createHash").Algorithm} Algorithm */
59
70
 
60
71
  /**
61
72
  * @param {Chunk} chunk a chunk
@@ -70,6 +81,25 @@ const chunkHasJs = (chunk, chunkGraph) => {
70
81
  );
71
82
  };
72
83
 
84
+ /**
85
+ * @param {Chunk} chunk a chunk
86
+ * @param {ChunkGraph} chunkGraph the chunk graph
87
+ * @returns {boolean} true, when a JS file is needed for this chunk
88
+ */
89
+ const chunkHasRuntimeOrJs = (chunk, chunkGraph) => {
90
+ if (
91
+ chunkGraph.getChunkModulesIterableBySourceType(
92
+ chunk,
93
+ WEBPACK_MODULE_TYPE_RUNTIME
94
+ )
95
+ )
96
+ return true;
97
+
98
+ return Boolean(
99
+ chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
100
+ );
101
+ };
102
+
73
103
  /**
74
104
  * @param {Module} module a module
75
105
  * @param {string} code the code
@@ -152,11 +182,11 @@ const printGeneratedCodeForStack = (module, code) => {
152
182
  * @property {SyncWaterfallHook<[Source, RenderContext]>} render
153
183
  * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup
154
184
  * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire
155
- * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout
185
+ * @property {SyncBailHook<[Module, RenderBootstrapContext], string | void>} inlineInRuntimeBailout
156
186
  * @property {SyncBailHook<[Module, RenderContext], string | void>} embedInRuntimeBailout
157
187
  * @property {SyncBailHook<[RenderContext], string | void>} strictRuntimeBailout
158
188
  * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash
159
- * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap
189
+ * @property {SyncBailHook<[Chunk, RenderContext], boolean | void>} useSourceMap
160
190
  */
161
191
 
162
192
  /** @type {WeakMap<Compilation, CompilationHooks>} */
@@ -263,13 +293,14 @@ class JavascriptModulesPlugin {
263
293
  } = options;
264
294
 
265
295
  const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null;
266
-
267
- let render;
268
296
  const filenameTemplate =
269
297
  JavascriptModulesPlugin.getChunkFilenameTemplate(
270
298
  chunk,
271
299
  outputOptions
272
300
  );
301
+
302
+ let render;
303
+
273
304
  if (hotUpdateChunk) {
274
305
  render = () =>
275
306
  this.renderChunk(
@@ -285,6 +316,10 @@ class JavascriptModulesPlugin {
285
316
  hooks
286
317
  );
287
318
  } else if (chunk.hasRuntime()) {
319
+ if (!chunkHasRuntimeOrJs(chunk, chunkGraph)) {
320
+ return result;
321
+ }
322
+
288
323
  render = () =>
289
324
  this.renderMain(
290
325
  {
@@ -370,7 +405,7 @@ class JavascriptModulesPlugin {
370
405
  hashFunction
371
406
  }
372
407
  } = compilation;
373
- const hash = createHash(hashFunction);
408
+ const hash = createHash(/** @type {Algorithm} */ (hashFunction));
374
409
  if (hashSalt) hash.update(hashSalt);
375
410
  if (chunk.hasRuntime()) {
376
411
  this.updateHashWithBootstrap(
@@ -420,7 +455,8 @@ class JavascriptModulesPlugin {
420
455
  const digest = /** @type {string} */ (hash.digest(hashDigest));
421
456
  chunk.contentHash.javascript = nonNumericOnlyHash(
422
457
  digest,
423
- hashDigestLength
458
+ /** @type {number} */
459
+ (hashDigestLength)
424
460
  );
425
461
  });
426
462
  compilation.hooks.additionalTreeRuntimeRequirements.tap(
@@ -439,7 +475,7 @@ class JavascriptModulesPlugin {
439
475
  compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
440
476
  const source = options.codeGenerationResult.sources.get("javascript");
441
477
  if (source === undefined) return;
442
- const { module, moduleObject } = options;
478
+ const { module } = options;
443
479
  const code = source.source();
444
480
 
445
481
  const fn = vm.runInThisContext(
@@ -449,6 +485,11 @@ class JavascriptModulesPlugin {
449
485
  lineOffset: -1
450
486
  }
451
487
  );
488
+
489
+ const moduleObject =
490
+ /** @type {ModuleObject} */
491
+ (options.moduleObject);
492
+
452
493
  try {
453
494
  fn.call(
454
495
  moduleObject.exports,
@@ -621,7 +662,8 @@ class JavascriptModulesPlugin {
621
662
  "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage"
622
663
  );
623
664
  } catch (err) {
624
- err.module = module;
665
+ /** @type {WebpackError} */
666
+ (err).module = module;
625
667
  throw err;
626
668
  }
627
669
  }
@@ -839,18 +881,25 @@ class JavascriptModulesPlugin {
839
881
  startupSource.add(`var ${RuntimeGlobals.exports} = {};\n`);
840
882
  }
841
883
 
842
- const renamedInlinedModule = this.renameInlineModule(
843
- allModules,
844
- renderContext,
845
- inlinedModules,
846
- chunkRenderContext,
847
- hooks
848
- );
884
+ const avoidEntryIife = compilation.options.optimization.avoidEntryIife;
885
+ /** @type {Map<Module, Source> | false} */
886
+ let renamedInlinedModule = false;
887
+ if (avoidEntryIife) {
888
+ renamedInlinedModule = this.getRenamedInlineModule(
889
+ allModules,
890
+ renderContext,
891
+ inlinedModules,
892
+ chunkRenderContext,
893
+ hooks,
894
+ allStrict,
895
+ Boolean(chunkModules)
896
+ );
897
+ }
849
898
 
850
899
  for (const m of inlinedModules) {
851
- const renderedModule =
852
- renamedInlinedModule.get(m) ||
853
- this.renderModule(m, chunkRenderContext, hooks, false);
900
+ const renderedModule = renamedInlinedModule
901
+ ? renamedInlinedModule.get(m)
902
+ : this.renderModule(m, chunkRenderContext, hooks, false);
854
903
 
855
904
  if (renderedModule) {
856
905
  const innerStrict =
@@ -863,18 +912,20 @@ class JavascriptModulesPlugin {
863
912
  const webpackExports =
864
913
  exports && m.exportsArgument === RuntimeGlobals.exports;
865
914
  const iife = innerStrict
866
- ? "it need to be in strict mode."
915
+ ? "it needs to be in strict mode."
867
916
  : inlinedModules.size > 1
868
917
  ? // TODO check globals and top-level declarations of other entries and chunk modules
869
918
  // to make a better decision
870
- "it need to be isolated against other entry modules."
871
- : exports && !webpackExports
872
- ? `it uses a non-standard name for the exports (${m.exportsArgument}).`
873
- : hooks.embedInRuntimeBailout.call(m, renderContext);
919
+ "it needs to be isolated against other entry modules."
920
+ : chunkModules && !renamedInlinedModule
921
+ ? "it needs to be isolated against other modules in the chunk."
922
+ : exports && !webpackExports
923
+ ? `it uses a non-standard name for the exports (${m.exportsArgument}).`
924
+ : hooks.embedInRuntimeBailout.call(m, renderContext);
874
925
  let footer;
875
926
  if (iife !== undefined) {
876
927
  startupSource.add(
877
- `// This entry need to be wrapped in an IIFE because ${iife}\n`
928
+ `// This entry needs to be wrapped in an IIFE because ${iife}\n`
878
929
  );
879
930
  const arrow = runtimeTemplate.supportsArrowFunction();
880
931
  if (arrow) {
@@ -1132,6 +1183,10 @@ class JavascriptModulesPlugin {
1132
1183
  entryModule,
1133
1184
  entrypoint
1134
1185
  ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
1186
+ if (!chunkGraph.getModuleSourceTypes(entryModule).has("javascript")) {
1187
+ i--;
1188
+ continue;
1189
+ }
1135
1190
  const chunks =
1136
1191
  /** @type {Entrypoint} */
1137
1192
  (entrypoint).chunks.filter(c => c !== chunk);
@@ -1420,25 +1475,43 @@ class JavascriptModulesPlugin {
1420
1475
  * @param {Set<Module>} inlinedModules inlinedModules
1421
1476
  * @param {ChunkRenderContext} chunkRenderContext chunkRenderContext
1422
1477
  * @param {CompilationHooks} hooks hooks
1423
- * @returns {Map<Module, Source>} renamed inlined modules
1478
+ * @param {boolean | undefined} allStrict allStrict
1479
+ * @param {boolean} hasChunkModules hasChunkModules
1480
+ * @returns {Map<Module, Source> | false} renamed inlined modules
1424
1481
  */
1425
- renameInlineModule(
1482
+ getRenamedInlineModule(
1426
1483
  allModules,
1427
1484
  renderContext,
1428
1485
  inlinedModules,
1429
1486
  chunkRenderContext,
1430
- hooks
1487
+ hooks,
1488
+ allStrict,
1489
+ hasChunkModules
1431
1490
  ) {
1432
- const { runtimeTemplate } = renderContext;
1491
+ const innerStrict =
1492
+ !allStrict &&
1493
+ allModules.every(m => /** @type {BuildInfo} */ (m.buildInfo).strict);
1494
+ const isMultipleEntries = inlinedModules.size > 1;
1495
+ const singleEntryWithModules = inlinedModules.size === 1 && hasChunkModules;
1496
+
1497
+ // TODO:
1498
+ // This step is before the IIFE reason calculation. Ideally, it should only be executed when this function can optimize the
1499
+ // IIFE reason. Otherwise, it should directly return false. There are four reasons now, we have skipped two already, the left
1500
+ // one is 'it uses a non-standard name for the exports'.
1501
+ if (isMultipleEntries || innerStrict || !singleEntryWithModules) {
1502
+ return false;
1503
+ }
1433
1504
 
1434
- /** @typedef {{ source: Source, ast: any, variables: Set<Variable>, usedInNonInlined: Set<Variable>}} InlinedModulesInfo */
1505
+ /** @type {Map<Module, Source>} */
1506
+ const renamedInlinedModules = new Map();
1507
+ const { runtimeTemplate } = renderContext;
1435
1508
 
1436
- /** @type {Map<Module, InlinedModulesInfo>} */
1509
+ /** @typedef {{ source: Source, module: Module, ast: any, variables: Set<Variable>, through: Set<Reference>, usedInNonInlined: Set<Variable>, moduleScope: Scope }} Info */
1510
+ /** @type {Map<Module, Info>} */
1437
1511
  const inlinedModulesToInfo = new Map();
1438
1512
  /** @type {Set<string>} */
1439
1513
  const nonInlinedModuleThroughIdentifiers = new Set();
1440
1514
  /** @type {Map<Module, Source>} */
1441
- const renamedInlinedModules = new Map();
1442
1515
 
1443
1516
  for (const m of allModules) {
1444
1517
  const isInlinedModule = inlinedModules && inlinedModules.has(m);
@@ -1468,8 +1541,11 @@ class JavascriptModulesPlugin {
1468
1541
  inlinedModulesToInfo.set(m, {
1469
1542
  source: moduleSource,
1470
1543
  ast,
1544
+ module: m,
1471
1545
  variables: new Set(moduleScope.variables),
1472
- usedInNonInlined: new Set()
1546
+ through: new Set(moduleScope.through),
1547
+ usedInNonInlined: new Set(),
1548
+ moduleScope
1473
1549
  });
1474
1550
  } else {
1475
1551
  for (const ref of globalScope.through) {
@@ -1480,7 +1556,10 @@ class JavascriptModulesPlugin {
1480
1556
 
1481
1557
  for (const [, { variables, usedInNonInlined }] of inlinedModulesToInfo) {
1482
1558
  for (const variable of variables) {
1483
- if (nonInlinedModuleThroughIdentifiers.has(variable.name)) {
1559
+ if (
1560
+ nonInlinedModuleThroughIdentifiers.has(variable.name) ||
1561
+ RESERVED_NAMES.has(variable.name)
1562
+ ) {
1484
1563
  usedInNonInlined.add(variable);
1485
1564
  }
1486
1565
  }
@@ -1494,39 +1573,70 @@ class JavascriptModulesPlugin {
1494
1573
  continue;
1495
1574
  }
1496
1575
 
1497
- const usedNames = new Set(
1498
- Array.from(
1499
- /** @type {InlinedModulesInfo} */
1500
- (inlinedModulesToInfo.get(m)).variables
1501
- ).map(v => v.name)
1576
+ const info = /** @type {Info} */ (inlinedModulesToInfo.get(m));
1577
+ const allUsedNames = new Set(
1578
+ Array.from(info.through, v => v.identifier.name)
1502
1579
  );
1503
1580
 
1504
1581
  for (const variable of usedInNonInlined) {
1582
+ allUsedNames.add(variable.name);
1583
+ }
1584
+
1585
+ for (const variable of info.variables) {
1586
+ allUsedNames.add(variable.name);
1505
1587
  const references = getAllReferences(variable);
1506
1588
  const allIdentifiers = new Set(
1507
1589
  references.map(r => r.identifier).concat(variable.identifiers)
1508
1590
  );
1509
1591
 
1510
- const newName = this.findNewName(
1511
- variable.name,
1512
- usedNames,
1513
- m.readableIdentifier(runtimeTemplate.requestShortener)
1592
+ const usedNamesInScopeInfo = new Map();
1593
+ const ignoredScopes = new Set();
1594
+
1595
+ const name = variable.name;
1596
+ const { usedNames, alreadyCheckedScopes } = getUsedNamesInScopeInfo(
1597
+ usedNamesInScopeInfo,
1598
+ info.module.identifier(),
1599
+ name
1514
1600
  );
1515
- usedNames.add(newName);
1516
- for (const identifier of allIdentifiers) {
1517
- const r = /** @type {Range} */ (identifier.range);
1518
- const path = getPathInAst(ast, identifier);
1519
- if (path && path.length > 1) {
1520
- const maybeProperty =
1521
- path[1].type === "AssignmentPattern" && path[1].left === path[0]
1522
- ? path[2]
1523
- : path[1];
1524
- if (maybeProperty.type === "Property" && maybeProperty.shorthand) {
1525
- source.insert(r[1], `: ${newName}`);
1526
- continue;
1601
+
1602
+ if (allUsedNames.has(name) || usedNames.has(name)) {
1603
+ const references = getAllReferences(variable);
1604
+ for (const ref of references) {
1605
+ addScopeSymbols(
1606
+ ref.from,
1607
+ usedNames,
1608
+ alreadyCheckedScopes,
1609
+ ignoredScopes
1610
+ );
1611
+ }
1612
+
1613
+ const newName = findNewName(
1614
+ variable.name,
1615
+ allUsedNames,
1616
+ usedNames,
1617
+ m.readableIdentifier(runtimeTemplate.requestShortener)
1618
+ );
1619
+ allUsedNames.add(newName);
1620
+ for (const identifier of allIdentifiers) {
1621
+ const r = /** @type {Range} */ (identifier.range);
1622
+ const path = getPathInAst(ast, identifier);
1623
+ if (path && path.length > 1) {
1624
+ const maybeProperty =
1625
+ path[1].type === "AssignmentPattern" && path[1].left === path[0]
1626
+ ? path[2]
1627
+ : path[1];
1628
+ if (
1629
+ maybeProperty.type === "Property" &&
1630
+ maybeProperty.shorthand
1631
+ ) {
1632
+ source.insert(r[1], `: ${newName}`);
1633
+ continue;
1634
+ }
1527
1635
  }
1636
+ source.replace(r[0], r[1] - 1, newName);
1528
1637
  }
1529
- source.replace(r[0], r[1] - 1, newName);
1638
+ } else {
1639
+ allUsedNames.add(name);
1530
1640
  }
1531
1641
  }
1532
1642
 
@@ -1535,38 +1645,6 @@ class JavascriptModulesPlugin {
1535
1645
 
1536
1646
  return renamedInlinedModules;
1537
1647
  }
1538
-
1539
- /**
1540
- * @param {string} oldName oldName
1541
- * @param {Set<string>} usedName usedName
1542
- * @param {string} extraInfo extraInfo
1543
- * @returns {string} extraInfo
1544
- */
1545
- findNewName(oldName, usedName, extraInfo) {
1546
- let name = oldName;
1547
-
1548
- // Remove uncool stuff
1549
- extraInfo = extraInfo.replace(
1550
- /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g,
1551
- ""
1552
- );
1553
- const splittedInfo = extraInfo.split("/");
1554
- while (splittedInfo.length) {
1555
- name = splittedInfo.pop() + (name ? `_${name}` : "");
1556
- const nameIdent = Template.toIdentifier(name);
1557
- if (!usedName.has(nameIdent)) {
1558
- return nameIdent;
1559
- }
1560
- }
1561
-
1562
- let i = 0;
1563
- let nameWithNumber = Template.toIdentifier(`${name}_${i}`);
1564
- while (usedName.has(nameWithNumber)) {
1565
- i++;
1566
- nameWithNumber = Template.toIdentifier(`${name}_${i}`);
1567
- }
1568
- return nameWithNumber;
1569
- }
1570
1648
  }
1571
1649
 
1572
1650
  module.exports = JavascriptModulesPlugin;