webpack 5.59.0 → 5.94.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 (570) hide show
  1. package/README.md +48 -38
  2. package/bin/webpack.js +34 -10
  3. package/hot/dev-server.js +19 -5
  4. package/hot/lazy-compilation-node.js +13 -1
  5. package/hot/lazy-compilation-web.js +9 -0
  6. package/hot/log-apply-result.js +5 -0
  7. package/hot/log.js +23 -4
  8. package/hot/only-dev-server.js +3 -2
  9. package/hot/poll.js +5 -2
  10. package/hot/signal.js +6 -2
  11. package/lib/APIPlugin.js +226 -122
  12. package/lib/AbstractMethodError.js +10 -5
  13. package/lib/AsyncDependenciesBlock.js +13 -5
  14. package/lib/AutomaticPrefetchPlugin.js +2 -1
  15. package/lib/BannerPlugin.js +33 -12
  16. package/lib/Cache.js +16 -12
  17. package/lib/CacheFacade.js +13 -16
  18. package/lib/CaseSensitiveModulesWarning.js +8 -8
  19. package/lib/Chunk.js +60 -33
  20. package/lib/ChunkGraph.js +207 -72
  21. package/lib/ChunkGroup.js +40 -20
  22. package/lib/ChunkTemplate.js +43 -0
  23. package/lib/CleanPlugin.js +117 -32
  24. package/lib/CodeGenerationResults.js +8 -7
  25. package/lib/CommentCompilationWarning.js +0 -1
  26. package/lib/CompatibilityPlugin.js +85 -46
  27. package/lib/Compilation.js +712 -392
  28. package/lib/Compiler.js +393 -172
  29. package/lib/ConcatenationScope.js +10 -13
  30. package/lib/ConditionalInitFragment.js +22 -14
  31. package/lib/ConstPlugin.js +104 -64
  32. package/lib/ContextExclusionPlugin.js +3 -3
  33. package/lib/ContextModule.js +283 -108
  34. package/lib/ContextModuleFactory.js +151 -63
  35. package/lib/ContextReplacementPlugin.js +25 -10
  36. package/lib/CssModule.js +166 -0
  37. package/lib/DefinePlugin.js +254 -148
  38. package/lib/DelegatedModule.js +29 -6
  39. package/lib/DelegatedModuleFactoryPlugin.js +42 -22
  40. package/lib/DelegatedPlugin.js +4 -0
  41. package/lib/DependenciesBlock.js +17 -2
  42. package/lib/Dependency.js +58 -29
  43. package/lib/DependencyTemplate.js +24 -3
  44. package/lib/DependencyTemplates.js +2 -2
  45. package/lib/DllEntryPlugin.js +18 -1
  46. package/lib/DllModule.js +21 -4
  47. package/lib/DllModuleFactory.js +2 -1
  48. package/lib/DllPlugin.js +9 -7
  49. package/lib/DllReferencePlugin.js +50 -19
  50. package/lib/EntryOptionPlugin.js +6 -1
  51. package/lib/EntryPlugin.js +7 -4
  52. package/lib/Entrypoint.js +2 -2
  53. package/lib/EnvironmentNotSupportAsyncWarning.js +52 -0
  54. package/lib/EnvironmentPlugin.js +5 -2
  55. package/lib/ErrorHelpers.js +65 -26
  56. package/lib/EvalDevToolModulePlugin.js +37 -13
  57. package/lib/EvalSourceMapDevToolPlugin.js +50 -20
  58. package/lib/ExportsInfo.js +234 -133
  59. package/lib/ExportsInfoApiPlugin.js +31 -15
  60. package/lib/ExternalModule.js +391 -129
  61. package/lib/ExternalModuleFactoryPlugin.js +65 -17
  62. package/lib/FileSystemInfo.js +1038 -523
  63. package/lib/FlagAllModulesAsUsedPlugin.js +27 -27
  64. package/lib/FlagDependencyExportsPlugin.js +352 -349
  65. package/lib/FlagDependencyUsagePlugin.js +10 -10
  66. package/lib/FlagEntryExportAsUsedPlugin.js +26 -23
  67. package/lib/Generator.js +16 -8
  68. package/lib/GraphHelpers.js +3 -2
  69. package/lib/HookWebpackError.js +11 -13
  70. package/lib/HotModuleReplacementPlugin.js +221 -128
  71. package/lib/IgnoreErrorModuleFactory.js +4 -4
  72. package/lib/IgnorePlugin.js +5 -4
  73. package/lib/IgnoreWarningsPlugin.js +6 -9
  74. package/lib/InitFragment.js +39 -15
  75. package/lib/JavascriptMetaInfoPlugin.js +27 -15
  76. package/lib/LibManifestPlugin.js +45 -16
  77. package/lib/LoaderOptionsPlugin.js +13 -3
  78. package/lib/MainTemplate.js +74 -21
  79. package/lib/Module.js +155 -34
  80. package/lib/ModuleBuildError.js +13 -11
  81. package/lib/ModuleDependencyError.js +6 -4
  82. package/lib/ModuleDependencyWarning.js +6 -4
  83. package/lib/ModuleError.js +10 -5
  84. package/lib/ModuleFactory.js +4 -4
  85. package/lib/ModuleFilenameHelpers.js +164 -54
  86. package/lib/ModuleGraph.js +93 -53
  87. package/lib/ModuleGraphConnection.js +27 -13
  88. package/lib/ModuleHashingError.js +29 -0
  89. package/lib/ModuleInfoHeaderPlugin.js +92 -33
  90. package/lib/ModuleNotFoundError.js +5 -2
  91. package/lib/ModuleParseError.js +17 -9
  92. package/lib/ModuleProfile.js +1 -0
  93. package/lib/ModuleRestoreError.js +3 -1
  94. package/lib/ModuleStoreError.js +3 -2
  95. package/lib/ModuleTemplate.js +33 -1
  96. package/lib/ModuleTypeConstants.js +168 -0
  97. package/lib/ModuleWarning.js +10 -5
  98. package/lib/MultiCompiler.js +115 -38
  99. package/lib/MultiStats.js +75 -33
  100. package/lib/MultiWatching.js +6 -2
  101. package/lib/NodeStuffPlugin.js +136 -37
  102. package/lib/NormalModule.js +437 -194
  103. package/lib/NormalModuleFactory.js +313 -116
  104. package/lib/NormalModuleReplacementPlugin.js +10 -4
  105. package/lib/NullFactory.js +1 -1
  106. package/lib/OptimizationStages.js +3 -3
  107. package/lib/Parser.js +1 -1
  108. package/lib/PlatformPlugin.js +39 -0
  109. package/lib/PrefetchPlugin.js +4 -0
  110. package/lib/ProgressPlugin.js +83 -28
  111. package/lib/ProvidePlugin.js +37 -19
  112. package/lib/RawModule.js +18 -5
  113. package/lib/RecordIdsPlugin.js +8 -8
  114. package/lib/RequireJsStuffPlugin.js +22 -15
  115. package/lib/ResolverFactory.js +8 -4
  116. package/lib/RuntimeGlobals.js +99 -65
  117. package/lib/RuntimeModule.js +17 -15
  118. package/lib/RuntimePlugin.js +116 -13
  119. package/lib/RuntimeTemplate.js +304 -102
  120. package/lib/SelfModuleFactory.js +12 -0
  121. package/lib/SizeFormatHelpers.js +2 -4
  122. package/lib/SourceMapDevToolModuleOptionsPlugin.js +4 -0
  123. package/lib/SourceMapDevToolPlugin.js +89 -42
  124. package/lib/Stats.js +12 -7
  125. package/lib/Template.js +30 -33
  126. package/lib/TemplatedPathPlugin.js +102 -34
  127. package/lib/UseStrictPlugin.js +37 -12
  128. package/lib/WarnCaseSensitiveModulesPlugin.js +12 -0
  129. package/lib/WarnDeprecatedOptionPlugin.js +6 -0
  130. package/lib/WatchIgnorePlugin.js +46 -13
  131. package/lib/Watching.js +139 -76
  132. package/lib/WebpackError.js +14 -5
  133. package/lib/WebpackIsIncludedPlugin.js +22 -13
  134. package/lib/WebpackOptionsApply.js +162 -56
  135. package/lib/WebpackOptionsDefaulter.js +10 -3
  136. package/lib/asset/AssetGenerator.js +351 -99
  137. package/lib/asset/AssetModulesPlugin.js +57 -33
  138. package/lib/asset/AssetParser.js +15 -6
  139. package/lib/asset/AssetSourceGenerator.js +30 -10
  140. package/lib/asset/AssetSourceParser.js +8 -2
  141. package/lib/asset/RawDataUrlModule.js +162 -0
  142. package/lib/async-modules/AwaitDependenciesInitFragment.js +16 -13
  143. package/lib/async-modules/InferAsyncModulesPlugin.js +1 -1
  144. package/lib/buildChunkGraph.js +376 -420
  145. package/lib/cache/AddManagedPathsPlugin.js +6 -1
  146. package/lib/cache/IdleFileCachePlugin.js +26 -13
  147. package/lib/cache/MemoryCachePlugin.js +1 -1
  148. package/lib/cache/MemoryWithGcCachePlugin.js +13 -7
  149. package/lib/cache/PackFileCacheStrategy.js +172 -94
  150. package/lib/cache/ResolverCachePlugin.js +115 -43
  151. package/lib/cache/getLazyHashedEtag.js +2 -2
  152. package/lib/cache/mergeEtags.js +16 -21
  153. package/lib/cli.js +195 -110
  154. package/lib/config/browserslistTargetHandler.js +106 -41
  155. package/lib/config/defaults.js +572 -154
  156. package/lib/config/normalization.js +361 -322
  157. package/lib/config/target.js +105 -66
  158. package/lib/container/ContainerEntryDependency.js +2 -1
  159. package/lib/container/ContainerEntryModule.js +27 -11
  160. package/lib/container/ContainerEntryModuleFactory.js +1 -1
  161. package/lib/container/ContainerExposedDependency.js +9 -0
  162. package/lib/container/ContainerPlugin.js +18 -12
  163. package/lib/container/ContainerReferencePlugin.js +1 -1
  164. package/lib/container/FallbackDependency.js +13 -0
  165. package/lib/container/FallbackItemDependency.js +3 -0
  166. package/lib/container/FallbackModule.js +19 -8
  167. package/lib/container/FallbackModuleFactory.js +1 -1
  168. package/lib/container/ModuleFederationPlugin.js +2 -0
  169. package/lib/container/RemoteModule.js +17 -4
  170. package/lib/container/RemoteRuntimeModule.js +31 -17
  171. package/lib/container/RemoteToExternalDependency.js +3 -0
  172. package/lib/container/options.js +18 -4
  173. package/lib/css/CssExportsGenerator.js +203 -0
  174. package/lib/css/CssGenerator.js +151 -0
  175. package/lib/css/CssLoadingRuntimeModule.js +592 -0
  176. package/lib/css/CssModulesPlugin.js +888 -0
  177. package/lib/css/CssParser.js +1049 -0
  178. package/lib/css/walkCssTokens.js +775 -0
  179. package/lib/debug/ProfilingPlugin.js +102 -54
  180. package/lib/dependencies/AMDDefineDependency.js +54 -10
  181. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +204 -61
  182. package/lib/dependencies/AMDPlugin.js +44 -24
  183. package/lib/dependencies/AMDRequireArrayDependency.js +34 -10
  184. package/lib/dependencies/AMDRequireContextDependency.js +15 -0
  185. package/lib/dependencies/AMDRequireDependenciesBlock.js +6 -0
  186. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +185 -54
  187. package/lib/dependencies/AMDRequireDependency.js +21 -6
  188. package/lib/dependencies/AMDRequireItemDependency.js +6 -0
  189. package/lib/dependencies/AMDRuntimeModules.js +4 -4
  190. package/lib/dependencies/CachedConstDependency.js +22 -1
  191. package/lib/dependencies/CommonJsDependencyHelpers.js +16 -2
  192. package/lib/dependencies/CommonJsExportRequireDependency.js +77 -47
  193. package/lib/dependencies/CommonJsExportsDependency.js +28 -5
  194. package/lib/dependencies/CommonJsExportsParserPlugin.js +111 -39
  195. package/lib/dependencies/CommonJsFullRequireDependency.js +42 -8
  196. package/lib/dependencies/CommonJsImportsParserPlugin.js +530 -130
  197. package/lib/dependencies/CommonJsPlugin.js +51 -26
  198. package/lib/dependencies/CommonJsRequireContextDependency.js +23 -2
  199. package/lib/dependencies/CommonJsRequireDependency.js +9 -1
  200. package/lib/dependencies/CommonJsSelfReferenceDependency.js +22 -8
  201. package/lib/dependencies/ConstDependency.js +12 -3
  202. package/lib/dependencies/ContextDependency.js +32 -5
  203. package/lib/dependencies/ContextDependencyHelpers.js +92 -62
  204. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +4 -1
  205. package/lib/dependencies/ContextElementDependency.js +41 -4
  206. package/lib/dependencies/CreateScriptUrlDependency.js +22 -1
  207. package/lib/dependencies/CriticalDependencyWarning.js +4 -1
  208. package/lib/dependencies/CssExportDependency.js +156 -0
  209. package/lib/dependencies/CssImportDependency.js +125 -0
  210. package/lib/dependencies/CssLocalIdentifierDependency.js +245 -0
  211. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +111 -0
  212. package/lib/dependencies/CssUrlDependency.js +164 -0
  213. package/lib/dependencies/DelegatedSourceDependency.js +3 -0
  214. package/lib/dependencies/DllEntryDependency.js +14 -0
  215. package/lib/dependencies/DynamicExports.js +15 -11
  216. package/lib/dependencies/ExportsInfoDependency.js +26 -5
  217. package/lib/dependencies/ExternalModuleDependency.js +109 -0
  218. package/lib/dependencies/ExternalModuleInitFragment.js +133 -0
  219. package/lib/dependencies/HarmonyAcceptDependency.js +11 -2
  220. package/lib/dependencies/HarmonyAcceptImportDependency.js +9 -4
  221. package/lib/dependencies/HarmonyCompatibilityDependency.js +6 -5
  222. package/lib/dependencies/HarmonyDetectionParserPlugin.js +29 -3
  223. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +152 -0
  224. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +96 -51
  225. package/lib/dependencies/HarmonyExportExpressionDependency.js +21 -4
  226. package/lib/dependencies/HarmonyExportHeaderDependency.js +13 -0
  227. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +216 -108
  228. package/lib/dependencies/HarmonyExportInitFragment.js +21 -9
  229. package/lib/dependencies/HarmonyExportSpecifierDependency.js +12 -0
  230. package/lib/dependencies/HarmonyExports.js +13 -7
  231. package/lib/dependencies/HarmonyImportDependency.js +65 -19
  232. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +268 -74
  233. package/lib/dependencies/HarmonyImportSideEffectDependency.js +11 -5
  234. package/lib/dependencies/HarmonyImportSpecifierDependency.js +180 -36
  235. package/lib/dependencies/HarmonyModulesPlugin.js +33 -5
  236. package/lib/dependencies/HarmonyTopLevelThisParserPlugin.js +15 -3
  237. package/lib/dependencies/ImportContextDependency.js +15 -2
  238. package/lib/dependencies/ImportDependency.js +50 -12
  239. package/lib/dependencies/ImportEagerDependency.js +11 -6
  240. package/lib/dependencies/ImportMetaContextDependency.js +42 -0
  241. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +301 -0
  242. package/lib/dependencies/ImportMetaContextPlugin.js +72 -0
  243. package/lib/dependencies/ImportMetaHotAcceptDependency.js +6 -0
  244. package/lib/dependencies/ImportMetaHotDeclineDependency.js +6 -0
  245. package/lib/dependencies/ImportMetaPlugin.js +128 -59
  246. package/lib/dependencies/ImportParserPlugin.js +153 -83
  247. package/lib/dependencies/ImportPlugin.js +21 -7
  248. package/lib/dependencies/ImportWeakDependency.js +11 -6
  249. package/lib/dependencies/JsonExportsDependency.js +38 -30
  250. package/lib/dependencies/LoaderDependency.js +14 -0
  251. package/lib/dependencies/LoaderImportDependency.js +14 -0
  252. package/lib/dependencies/LoaderPlugin.js +54 -40
  253. package/lib/dependencies/LocalModule.js +17 -1
  254. package/lib/dependencies/LocalModuleDependency.js +15 -0
  255. package/lib/dependencies/LocalModulesHelpers.js +22 -4
  256. package/lib/dependencies/ModuleDecoratorDependency.js +9 -1
  257. package/lib/dependencies/ModuleDependency.js +24 -7
  258. package/lib/dependencies/ModuleDependencyTemplateAsId.js +2 -1
  259. package/lib/dependencies/ModuleHotAcceptDependency.js +6 -0
  260. package/lib/dependencies/ModuleHotDeclineDependency.js +6 -0
  261. package/lib/dependencies/PrefetchDependency.js +3 -0
  262. package/lib/dependencies/ProvidedDependency.js +43 -8
  263. package/lib/dependencies/PureExpressionDependency.js +73 -39
  264. package/lib/dependencies/RequireContextDependency.js +6 -16
  265. package/lib/dependencies/RequireContextDependencyParserPlugin.js +14 -6
  266. package/lib/dependencies/RequireContextPlugin.js +20 -7
  267. package/lib/dependencies/RequireEnsureDependenciesBlock.js +7 -0
  268. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +29 -12
  269. package/lib/dependencies/RequireEnsureDependency.js +16 -2
  270. package/lib/dependencies/RequireEnsureItemDependency.js +3 -0
  271. package/lib/dependencies/RequireEnsurePlugin.js +27 -7
  272. package/lib/dependencies/RequireHeaderDependency.js +14 -1
  273. package/lib/dependencies/RequireIncludeDependency.js +6 -1
  274. package/lib/dependencies/RequireIncludeDependencyParserPlugin.js +29 -5
  275. package/lib/dependencies/RequireIncludePlugin.js +25 -5
  276. package/lib/dependencies/RequireResolveContextDependency.js +19 -2
  277. package/lib/dependencies/RequireResolveDependency.js +8 -1
  278. package/lib/dependencies/RequireResolveHeaderDependency.js +18 -0
  279. package/lib/dependencies/RuntimeRequirementsDependency.js +9 -1
  280. package/lib/dependencies/StaticExportsDependency.js +8 -0
  281. package/lib/dependencies/SystemPlugin.js +49 -22
  282. package/lib/dependencies/SystemRuntimeModule.js +1 -1
  283. package/lib/dependencies/URLDependency.js +20 -13
  284. package/lib/dependencies/URLPlugin.js +115 -27
  285. package/lib/dependencies/UnsupportedDependency.js +13 -0
  286. package/lib/dependencies/WebAssemblyExportImportedDependency.js +14 -0
  287. package/lib/dependencies/WebAssemblyImportDependency.js +9 -1
  288. package/lib/dependencies/WebpackIsIncludedDependency.js +6 -1
  289. package/lib/dependencies/WorkerDependency.js +47 -3
  290. package/lib/dependencies/WorkerPlugin.js +143 -59
  291. package/lib/dependencies/getFunctionExpression.js +9 -0
  292. package/lib/dependencies/processExportInfo.js +3 -1
  293. package/lib/electron/ElectronTargetPlugin.js +1 -0
  294. package/lib/esm/ExportWebpackRequireRuntimeModule.js +3 -2
  295. package/lib/esm/ModuleChunkFormatPlugin.js +92 -55
  296. package/lib/esm/ModuleChunkLoadingPlugin.js +12 -1
  297. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +141 -25
  298. package/lib/formatLocation.js +1 -2
  299. package/lib/hmr/HotModuleReplacement.runtime.js +37 -25
  300. package/lib/hmr/HotModuleReplacementRuntimeModule.js +2 -1
  301. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +13 -15
  302. package/lib/hmr/LazyCompilationPlugin.js +94 -41
  303. package/lib/hmr/lazyCompilationBackend.js +107 -44
  304. package/lib/ids/ChunkModuleIdRangePlugin.js +12 -3
  305. package/lib/ids/DeterministicChunkIdsPlugin.js +13 -6
  306. package/lib/ids/DeterministicModuleIdsPlugin.js +59 -35
  307. package/lib/ids/HashedModuleIdsPlugin.js +24 -16
  308. package/lib/ids/IdHelpers.js +59 -49
  309. package/lib/ids/NamedChunkIdsPlugin.js +13 -1
  310. package/lib/ids/NamedModuleIdsPlugin.js +20 -12
  311. package/lib/ids/NaturalModuleIdsPlugin.js +10 -13
  312. package/lib/ids/OccurrenceChunkIdsPlugin.js +6 -2
  313. package/lib/ids/OccurrenceModuleIdsPlugin.js +14 -11
  314. package/lib/ids/SyncModuleIdsPlugin.js +146 -0
  315. package/lib/index.js +44 -5
  316. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +9 -7
  317. package/lib/javascript/BasicEvaluatedExpression.js +133 -19
  318. package/lib/javascript/ChunkHelpers.js +33 -0
  319. package/lib/javascript/CommonJsChunkFormatPlugin.js +18 -15
  320. package/lib/javascript/EnableChunkLoadingPlugin.js +11 -6
  321. package/lib/javascript/JavascriptGenerator.js +37 -6
  322. package/lib/javascript/JavascriptModulesPlugin.js +523 -295
  323. package/lib/javascript/JavascriptParser.js +1591 -574
  324. package/lib/javascript/JavascriptParserHelpers.js +58 -37
  325. package/lib/javascript/StartupHelpers.js +69 -47
  326. package/lib/json/JsonData.js +33 -0
  327. package/lib/json/JsonGenerator.js +29 -21
  328. package/lib/json/JsonModulesPlugin.js +13 -7
  329. package/lib/json/JsonParser.js +30 -16
  330. package/lib/library/AbstractLibraryPlugin.js +6 -2
  331. package/lib/library/AmdLibraryPlugin.js +34 -18
  332. package/lib/library/AssignLibraryPlugin.js +68 -32
  333. package/lib/library/EnableLibraryPlugin.js +39 -14
  334. package/lib/library/ExportPropertyLibraryPlugin.js +14 -5
  335. package/lib/library/JsonpLibraryPlugin.js +4 -3
  336. package/lib/library/ModernModuleLibraryPlugin.js +144 -0
  337. package/lib/library/ModuleLibraryPlugin.js +12 -7
  338. package/lib/library/SystemLibraryPlugin.js +6 -4
  339. package/lib/library/UmdLibraryPlugin.js +119 -100
  340. package/lib/logging/Logger.js +59 -6
  341. package/lib/logging/createConsoleLogger.js +25 -40
  342. package/lib/logging/runtime.js +8 -9
  343. package/lib/logging/truncateArgs.js +9 -8
  344. package/lib/node/CommonJsChunkLoadingPlugin.js +18 -2
  345. package/lib/node/NodeEnvironmentPlugin.js +14 -8
  346. package/lib/node/NodeTargetPlugin.js +7 -0
  347. package/lib/node/NodeTemplatePlugin.js +10 -2
  348. package/lib/node/NodeWatchFileSystem.js +100 -50
  349. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +51 -26
  350. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +13 -2
  351. package/lib/node/ReadFileCompileWasmPlugin.js +21 -3
  352. package/lib/node/RequireChunkLoadingRuntimeModule.js +49 -26
  353. package/lib/node/nodeConsole.js +48 -31
  354. package/lib/optimize/AggressiveMergingPlugin.js +10 -4
  355. package/lib/optimize/AggressiveSplittingPlugin.js +26 -21
  356. package/lib/optimize/ConcatenatedModule.js +353 -212
  357. package/lib/optimize/EnsureChunkConditionsPlugin.js +4 -1
  358. package/lib/optimize/FlagIncludedChunksPlugin.js +14 -8
  359. package/lib/optimize/InnerGraph.js +30 -25
  360. package/lib/optimize/InnerGraphPlugin.js +105 -64
  361. package/lib/optimize/LimitChunkCountPlugin.js +32 -9
  362. package/lib/optimize/MangleExportsPlugin.js +7 -2
  363. package/lib/optimize/MinMaxSizeWarning.js +6 -1
  364. package/lib/optimize/ModuleConcatenationPlugin.js +150 -83
  365. package/lib/optimize/RealContentHashPlugin.js +99 -43
  366. package/lib/optimize/RemoveParentModulesPlugin.js +131 -48
  367. package/lib/optimize/RuntimeChunkPlugin.js +15 -2
  368. package/lib/optimize/SideEffectsFlagPlugin.js +119 -63
  369. package/lib/optimize/SplitChunksPlugin.js +129 -78
  370. package/lib/performance/SizeLimitsPlugin.js +22 -8
  371. package/lib/prefetch/ChunkPrefetchFunctionRuntimeModule.js +4 -2
  372. package/lib/prefetch/ChunkPrefetchPreloadPlugin.js +4 -1
  373. package/lib/prefetch/ChunkPrefetchStartupRuntimeModule.js +8 -5
  374. package/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +5 -3
  375. package/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +5 -3
  376. package/lib/rules/BasicEffectRulePlugin.js +7 -1
  377. package/lib/rules/BasicMatcherRulePlugin.js +8 -1
  378. package/lib/rules/ObjectMatcherRulePlugin.js +19 -2
  379. package/lib/rules/RuleSetCompiler.js +53 -32
  380. package/lib/rules/UseEffectRulePlugin.js +42 -36
  381. package/lib/runtime/AsyncModuleRuntimeModule.js +56 -69
  382. package/lib/runtime/AutoPublicPathRuntimeModule.js +25 -9
  383. package/lib/runtime/BaseUriRuntimeModule.js +35 -0
  384. package/lib/runtime/ChunkNameRuntimeModule.js +1 -1
  385. package/lib/runtime/CompatGetDefaultExportRuntimeModule.js +5 -2
  386. package/lib/runtime/CompatRuntimeModule.js +7 -2
  387. package/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +7 -4
  388. package/lib/runtime/CreateScriptRuntimeModule.js +38 -0
  389. package/lib/runtime/CreateScriptUrlRuntimeModule.js +13 -36
  390. package/lib/runtime/DefinePropertyGettersRuntimeModule.js +6 -3
  391. package/lib/runtime/EnsureChunkRuntimeModule.js +29 -15
  392. package/lib/runtime/GetChunkFilenameRuntimeModule.js +56 -43
  393. package/lib/runtime/GetFullHashRuntimeModule.js +4 -3
  394. package/lib/runtime/GetMainFilenameRuntimeModule.js +5 -2
  395. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +98 -0
  396. package/lib/runtime/GlobalRuntimeModule.js +1 -1
  397. package/lib/runtime/HasOwnPropertyRuntimeModule.js +5 -2
  398. package/lib/runtime/LoadScriptRuntimeModule.js +61 -45
  399. package/lib/runtime/MakeNamespaceObjectRuntimeModule.js +5 -2
  400. package/lib/runtime/NonceRuntimeModule.js +24 -0
  401. package/lib/runtime/OnChunksLoadedRuntimeModule.js +4 -2
  402. package/lib/runtime/PublicPathRuntimeModule.js +9 -2
  403. package/lib/runtime/RelativeUrlRuntimeModule.js +5 -2
  404. package/lib/runtime/RuntimeIdRuntimeModule.js +6 -2
  405. package/lib/runtime/StartupChunkDependenciesPlugin.js +15 -0
  406. package/lib/runtime/StartupChunkDependenciesRuntimeModule.js +36 -28
  407. package/lib/runtime/StartupEntrypointRuntimeModule.js +13 -9
  408. package/lib/runtime/SystemContextRuntimeModule.js +1 -1
  409. package/lib/schemes/DataUriPlugin.js +16 -3
  410. package/lib/schemes/HttpUriPlugin.js +336 -120
  411. package/lib/serialization/ArraySerializer.js +22 -6
  412. package/lib/serialization/BinaryMiddleware.js +212 -33
  413. package/lib/serialization/DateObjectSerializer.js +16 -4
  414. package/lib/serialization/ErrorObjectSerializer.js +23 -6
  415. package/lib/serialization/FileMiddleware.js +187 -86
  416. package/lib/serialization/MapObjectSerializer.js +25 -8
  417. package/lib/serialization/NullPrototypeObjectSerializer.js +26 -8
  418. package/lib/serialization/ObjectMiddleware.js +96 -66
  419. package/lib/serialization/PlainObjectSerializer.js +51 -14
  420. package/lib/serialization/RegExpObjectSerializer.js +17 -5
  421. package/lib/serialization/Serializer.js +23 -5
  422. package/lib/serialization/SerializerMiddleware.js +8 -8
  423. package/lib/serialization/SetObjectSerializer.js +22 -6
  424. package/lib/serialization/SingleItemMiddleware.js +2 -2
  425. package/lib/serialization/types.js +2 -2
  426. package/lib/sharing/ConsumeSharedFallbackDependency.js +3 -0
  427. package/lib/sharing/ConsumeSharedModule.js +40 -17
  428. package/lib/sharing/ConsumeSharedPlugin.js +139 -102
  429. package/lib/sharing/ConsumeSharedRuntimeModule.js +144 -130
  430. package/lib/sharing/ProvideForSharedDependency.js +0 -1
  431. package/lib/sharing/ProvideSharedDependency.js +17 -0
  432. package/lib/sharing/ProvideSharedModule.js +19 -6
  433. package/lib/sharing/ProvideSharedModuleFactory.js +1 -1
  434. package/lib/sharing/ProvideSharedPlugin.js +37 -30
  435. package/lib/sharing/SharePlugin.js +2 -2
  436. package/lib/sharing/ShareRuntimeModule.js +20 -10
  437. package/lib/sharing/resolveMatchedConfigs.js +6 -5
  438. package/lib/sharing/utils.js +338 -34
  439. package/lib/stats/DefaultStatsFactoryPlugin.js +660 -396
  440. package/lib/stats/DefaultStatsPresetPlugin.js +85 -25
  441. package/lib/stats/DefaultStatsPrinterPlugin.js +525 -145
  442. package/lib/stats/StatsFactory.js +128 -57
  443. package/lib/stats/StatsPrinter.js +77 -46
  444. package/lib/util/ArrayHelpers.js +35 -1
  445. package/lib/util/ArrayQueue.js +15 -22
  446. package/lib/util/AsyncQueue.js +37 -16
  447. package/lib/util/IterableHelpers.js +3 -4
  448. package/lib/util/LazyBucketSortedSet.js +60 -44
  449. package/lib/util/LazySet.js +11 -2
  450. package/lib/util/MapHelpers.js +17 -5
  451. package/lib/util/ParallelismFactorCalculator.js +11 -1
  452. package/lib/util/Queue.js +9 -3
  453. package/lib/util/Semaphore.js +4 -7
  454. package/lib/util/SetHelpers.js +5 -5
  455. package/lib/util/SortableSet.js +19 -6
  456. package/lib/util/StackedCacheMap.js +33 -3
  457. package/lib/util/StackedMap.js +1 -3
  458. package/lib/util/StringXor.js +46 -0
  459. package/lib/util/TupleQueue.js +9 -3
  460. package/lib/util/TupleSet.js +15 -5
  461. package/lib/util/URLAbsoluteSpecifier.js +8 -8
  462. package/lib/util/WeakTupleMap.js +70 -28
  463. package/lib/util/binarySearchBounds.js +51 -9
  464. package/lib/util/chainedImports.js +97 -0
  465. package/lib/util/cleverMerge.js +51 -36
  466. package/lib/util/comparators.js +146 -83
  467. package/lib/util/compileBooleanMatcher.js +35 -7
  468. package/lib/util/conventions.js +126 -0
  469. package/lib/util/create-schema-validation.js +9 -2
  470. package/lib/util/createHash.js +49 -14
  471. package/lib/util/deprecation.js +48 -15
  472. package/lib/util/deterministicGrouping.js +71 -39
  473. package/lib/util/extractUrlAndGlobal.js +3 -0
  474. package/lib/util/findGraphRoots.js +7 -5
  475. package/lib/util/fs.js +419 -94
  476. package/lib/util/hash/BatchedHash.js +10 -4
  477. package/lib/util/hash/md4.js +20 -0
  478. package/lib/util/hash/wasm-hash.js +163 -0
  479. package/lib/util/hash/xxhash64.js +7 -141
  480. package/lib/util/identifier.js +140 -93
  481. package/lib/util/internalSerializables.js +22 -0
  482. package/lib/util/makeSerializable.js +7 -0
  483. package/lib/util/memoize.js +10 -10
  484. package/lib/util/mergeScope.js +76 -0
  485. package/lib/util/nonNumericOnlyHash.js +22 -0
  486. package/lib/util/numberHash.js +84 -34
  487. package/lib/util/objectToMap.js +0 -1
  488. package/lib/util/processAsyncTree.js +7 -1
  489. package/lib/util/propertyAccess.js +7 -55
  490. package/lib/util/propertyName.js +77 -0
  491. package/lib/util/registerExternalSerializer.js +2 -2
  492. package/lib/util/runtime.js +188 -133
  493. package/lib/util/semver.js +64 -56
  494. package/lib/util/serialization.js +26 -1
  495. package/lib/util/smartGrouping.js +10 -10
  496. package/lib/util/source.js +1 -1
  497. package/lib/validateSchema.js +6 -2
  498. package/lib/wasm/EnableWasmLoadingPlugin.js +9 -4
  499. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +70 -30
  500. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +9 -1
  501. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +34 -16
  502. package/lib/wasm-async/AsyncWebAssemblyModulesPlugin.js +32 -12
  503. package/lib/wasm-async/AsyncWebAssemblyParser.js +17 -4
  504. package/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +72 -31
  505. package/lib/wasm-sync/WasmFinalizeExportsPlugin.js +17 -6
  506. package/lib/wasm-sync/WebAssemblyGenerator.js +72 -52
  507. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +5 -4
  508. package/lib/wasm-sync/WebAssemblyModulesPlugin.js +53 -43
  509. package/lib/wasm-sync/WebAssemblyParser.js +23 -9
  510. package/lib/wasm-sync/WebAssemblyUtils.js +5 -4
  511. package/lib/web/FetchCompileAsyncWasmPlugin.js +11 -1
  512. package/lib/web/FetchCompileWasmPlugin.js +59 -42
  513. package/lib/web/JsonpChunkLoadingPlugin.js +9 -0
  514. package/lib/web/JsonpChunkLoadingRuntimeModule.js +71 -41
  515. package/lib/webpack.js +43 -12
  516. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +15 -12
  517. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +55 -40
  518. package/module.d.ts +233 -0
  519. package/package.json +85 -139
  520. package/schemas/WebpackOptions.check.js +1 -1
  521. package/schemas/WebpackOptions.json +679 -47
  522. package/schemas/plugins/BannerPlugin.check.js +1 -1
  523. package/schemas/plugins/BannerPlugin.json +9 -1
  524. package/schemas/plugins/DllReferencePlugin.check.js +1 -1
  525. package/schemas/plugins/HashedModuleIdsPlugin.check.js +1 -1
  526. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  527. package/schemas/plugins/SourceMapDevToolPlugin.check.js +1 -1
  528. package/schemas/plugins/SourceMapDevToolPlugin.json +4 -0
  529. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  530. package/schemas/plugins/asset/AssetInlineGeneratorOptions.check.js +1 -1
  531. package/schemas/plugins/asset/AssetParserOptions.check.js +1 -1
  532. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  533. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  534. package/schemas/plugins/container/ContainerPlugin.json +10 -1
  535. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  536. package/schemas/plugins/container/ContainerReferencePlugin.json +2 -0
  537. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  538. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  539. package/schemas/plugins/container/ModuleFederationPlugin.json +12 -1
  540. package/schemas/plugins/css/CssAutoGeneratorOptions.check.d.ts +7 -0
  541. package/schemas/plugins/css/CssAutoGeneratorOptions.check.js +6 -0
  542. package/schemas/plugins/css/CssAutoGeneratorOptions.json +3 -0
  543. package/schemas/plugins/css/CssAutoParserOptions.check.d.ts +7 -0
  544. package/schemas/plugins/css/CssAutoParserOptions.check.js +6 -0
  545. package/schemas/plugins/css/CssAutoParserOptions.json +3 -0
  546. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +7 -0
  547. package/schemas/plugins/css/CssGeneratorOptions.check.js +6 -0
  548. package/schemas/plugins/css/CssGeneratorOptions.json +3 -0
  549. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.d.ts +7 -0
  550. package/schemas/plugins/css/CssGlobalGeneratorOptions.check.js +6 -0
  551. package/schemas/plugins/css/CssGlobalGeneratorOptions.json +3 -0
  552. package/schemas/plugins/css/CssGlobalParserOptions.check.d.ts +7 -0
  553. package/schemas/plugins/css/CssGlobalParserOptions.check.js +6 -0
  554. package/schemas/plugins/css/CssGlobalParserOptions.json +3 -0
  555. package/schemas/plugins/css/CssModuleGeneratorOptions.check.d.ts +7 -0
  556. package/schemas/plugins/css/CssModuleGeneratorOptions.check.js +6 -0
  557. package/schemas/plugins/css/CssModuleGeneratorOptions.json +3 -0
  558. package/schemas/plugins/css/CssModuleParserOptions.check.d.ts +7 -0
  559. package/schemas/plugins/css/CssModuleParserOptions.check.js +6 -0
  560. package/schemas/plugins/css/CssModuleParserOptions.json +3 -0
  561. package/schemas/plugins/css/CssParserOptions.check.d.ts +7 -0
  562. package/schemas/plugins/css/CssParserOptions.check.js +6 -0
  563. package/schemas/plugins/css/CssParserOptions.json +3 -0
  564. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js +1 -1
  565. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.js +1 -1
  566. package/schemas/plugins/optimize/MinChunkSizePlugin.check.js +1 -1
  567. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -1
  568. package/schemas/plugins/schemes/HttpUriPlugin.json +4 -0
  569. package/schemas/plugins/sharing/SharePlugin.check.js +1 -1
  570. package/types.d.ts +5026 -1756
@@ -5,6 +5,7 @@
5
5
 
6
6
  "use strict";
7
7
 
8
+ const eslintScope = require("eslint-scope");
8
9
  const { SyncWaterfallHook, SyncHook, SyncBailHook } = require("tapable");
9
10
  const vm = require("vm");
10
11
  const {
@@ -12,32 +13,48 @@ const {
12
13
  OriginalSource,
13
14
  PrefixSource,
14
15
  RawSource,
15
- CachedSource
16
+ CachedSource,
17
+ ReplaceSource
16
18
  } = require("webpack-sources");
17
19
  const Compilation = require("../Compilation");
18
20
  const { tryRunOrWebpackError } = require("../HookWebpackError");
19
21
  const HotUpdateChunk = require("../HotUpdateChunk");
20
22
  const InitFragment = require("../InitFragment");
23
+ const {
24
+ JAVASCRIPT_MODULE_TYPE_AUTO,
25
+ JAVASCRIPT_MODULE_TYPE_DYNAMIC,
26
+ JAVASCRIPT_MODULE_TYPE_ESM,
27
+ WEBPACK_MODULE_TYPE_RUNTIME
28
+ } = require("../ModuleTypeConstants");
21
29
  const RuntimeGlobals = require("../RuntimeGlobals");
22
30
  const Template = require("../Template");
23
31
  const { last, someInIterable } = require("../util/IterableHelpers");
24
32
  const StringXor = require("../util/StringXor");
25
33
  const { compareModulesByIdentifier } = require("../util/comparators");
26
34
  const createHash = require("../util/createHash");
35
+ const { getPathInAst, getAllReferences } = require("../util/mergeScope");
36
+ const nonNumericOnlyHash = require("../util/nonNumericOnlyHash");
27
37
  const { intersectRuntime } = require("../util/runtime");
28
38
  const JavascriptGenerator = require("./JavascriptGenerator");
29
39
  const JavascriptParser = require("./JavascriptParser");
30
40
 
41
+ /** @typedef {import("eslint-scope").Scope} Scope */
42
+ /** @typedef {import("eslint-scope").Variable} Variable */
31
43
  /** @typedef {import("webpack-sources").Source} Source */
44
+ /** @typedef {import("../../declarations/WebpackOptions").Output} OutputOptions */
32
45
  /** @typedef {import("../Chunk")} Chunk */
33
46
  /** @typedef {import("../ChunkGraph")} ChunkGraph */
34
47
  /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
35
48
  /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
36
49
  /** @typedef {import("../Compiler")} Compiler */
37
50
  /** @typedef {import("../DependencyTemplates")} DependencyTemplates */
51
+ /** @typedef {import("../Entrypoint")} Entrypoint */
38
52
  /** @typedef {import("../Module")} Module */
53
+ /** @typedef {import("../Module").BuildInfo} BuildInfo */
39
54
  /** @typedef {import("../ModuleGraph")} ModuleGraph */
40
55
  /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
56
+ /** @typedef {import("../TemplatedPathPlugin").TemplatePath} TemplatePath */
57
+ /** @typedef {import("../javascript/JavascriptParser").Range} Range */
41
58
  /** @typedef {import("../util/Hash")} Hash */
42
59
 
43
60
  /**
@@ -48,35 +65,48 @@ const JavascriptParser = require("./JavascriptParser");
48
65
  const chunkHasJs = (chunk, chunkGraph) => {
49
66
  if (chunkGraph.getNumberOfEntryModules(chunk) > 0) return true;
50
67
 
51
- return chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
52
- ? true
53
- : false;
68
+ return Boolean(
69
+ chunkGraph.getChunkModulesIterableBySourceType(chunk, "javascript")
70
+ );
54
71
  };
55
72
 
73
+ /**
74
+ * @param {Module} module a module
75
+ * @param {string} code the code
76
+ * @returns {string} generated code for the stack
77
+ */
56
78
  const printGeneratedCodeForStack = (module, code) => {
57
79
  const lines = code.split("\n");
58
80
  const n = `${lines.length}`.length;
59
81
  return `\n\nGenerated code for ${module.identifier()}\n${lines
60
- .map((line, i, lines) => {
61
- const iStr = `${i + 1}`;
62
- return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`;
63
- })
82
+ .map(
83
+ /**
84
+ * @param {string} line the line
85
+ * @param {number} i the index
86
+ * @param {string[]} lines the lines
87
+ * @returns {string} the line with line number
88
+ */
89
+ (line, i, lines) => {
90
+ const iStr = `${i + 1}`;
91
+ return `${" ".repeat(n - iStr.length)}${iStr} | ${line}`;
92
+ }
93
+ )
64
94
  .join("\n")}`;
65
95
  };
66
96
 
67
97
  /**
68
- * @typedef {Object} RenderContext
98
+ * @typedef {object} RenderContext
69
99
  * @property {Chunk} chunk the chunk
70
100
  * @property {DependencyTemplates} dependencyTemplates the dependency templates
71
101
  * @property {RuntimeTemplate} runtimeTemplate the runtime template
72
102
  * @property {ModuleGraph} moduleGraph the module graph
73
103
  * @property {ChunkGraph} chunkGraph the chunk graph
74
104
  * @property {CodeGenerationResults} codeGenerationResults results of code generation
75
- * @property {boolean} strictMode rendering in strict context
105
+ * @property {boolean | undefined} strictMode rendering in strict context
76
106
  */
77
107
 
78
108
  /**
79
- * @typedef {Object} MainRenderContext
109
+ * @typedef {object} MainRenderContext
80
110
  * @property {Chunk} chunk the chunk
81
111
  * @property {DependencyTemplates} dependencyTemplates the dependency templates
82
112
  * @property {RuntimeTemplate} runtimeTemplate the runtime template
@@ -84,11 +114,11 @@ const printGeneratedCodeForStack = (module, code) => {
84
114
  * @property {ChunkGraph} chunkGraph the chunk graph
85
115
  * @property {CodeGenerationResults} codeGenerationResults results of code generation
86
116
  * @property {string} hash hash to be used for render call
87
- * @property {boolean} strictMode rendering in strict context
117
+ * @property {boolean | undefined} strictMode rendering in strict context
88
118
  */
89
119
 
90
120
  /**
91
- * @typedef {Object} ChunkRenderContext
121
+ * @typedef {object} ChunkRenderContext
92
122
  * @property {Chunk} chunk the chunk
93
123
  * @property {DependencyTemplates} dependencyTemplates the dependency templates
94
124
  * @property {RuntimeTemplate} runtimeTemplate the runtime template
@@ -96,12 +126,13 @@ const printGeneratedCodeForStack = (module, code) => {
96
126
  * @property {ChunkGraph} chunkGraph the chunk graph
97
127
  * @property {CodeGenerationResults} codeGenerationResults results of code generation
98
128
  * @property {InitFragment<ChunkRenderContext>[]} chunkInitFragments init fragments for the chunk
99
- * @property {boolean} strictMode rendering in strict context
129
+ * @property {boolean | undefined} strictMode rendering in strict context
100
130
  */
101
131
 
102
132
  /**
103
- * @typedef {Object} RenderBootstrapContext
133
+ * @typedef {object} RenderBootstrapContext
104
134
  * @property {Chunk} chunk the chunk
135
+ * @property {CodeGenerationResults} codeGenerationResults results of code generation
105
136
  * @property {RuntimeTemplate} runtimeTemplate the runtime template
106
137
  * @property {ModuleGraph} moduleGraph the module graph
107
138
  * @property {ChunkGraph} chunkGraph the chunk graph
@@ -111,7 +142,7 @@ const printGeneratedCodeForStack = (module, code) => {
111
142
  /** @typedef {RenderContext & { inlined: boolean }} StartupRenderContext */
112
143
 
113
144
  /**
114
- * @typedef {Object} CompilationHooks
145
+ * @typedef {object} CompilationHooks
115
146
  * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContent
116
147
  * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModuleContainer
117
148
  * @property {SyncWaterfallHook<[Source, Module, ChunkRenderContext]>} renderModulePackage
@@ -122,8 +153,8 @@ const printGeneratedCodeForStack = (module, code) => {
122
153
  * @property {SyncWaterfallHook<[Source, Module, StartupRenderContext]>} renderStartup
123
154
  * @property {SyncWaterfallHook<[string, RenderBootstrapContext]>} renderRequire
124
155
  * @property {SyncBailHook<[Module, RenderBootstrapContext], string>} inlineInRuntimeBailout
125
- * @property {SyncBailHook<[Module, RenderContext], string>} embedInRuntimeBailout
126
- * @property {SyncBailHook<[RenderContext], string>} strictRuntimeBailout
156
+ * @property {SyncBailHook<[Module, RenderContext], string | void>} embedInRuntimeBailout
157
+ * @property {SyncBailHook<[RenderContext], string | void>} strictRuntimeBailout
127
158
  * @property {SyncHook<[Chunk, Hash, ChunkHashContext]>} chunkHash
128
159
  * @property {SyncBailHook<[Chunk, RenderContext], boolean>} useSourceMap
129
160
  */
@@ -131,6 +162,10 @@ const printGeneratedCodeForStack = (module, code) => {
131
162
  /** @type {WeakMap<Compilation, CompilationHooks>} */
132
163
  const compilationHooksMap = new WeakMap();
133
164
 
165
+ const PLUGIN_NAME = "JavascriptModulesPlugin";
166
+
167
+ /** @typedef {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} Bootstrap */
168
+
134
169
  class JavascriptModulesPlugin {
135
170
  /**
136
171
  * @param {Compilation} compilation the compilation
@@ -194,155 +229,138 @@ class JavascriptModulesPlugin {
194
229
  */
195
230
  apply(compiler) {
196
231
  compiler.hooks.compilation.tap(
197
- "JavascriptModulesPlugin",
232
+ PLUGIN_NAME,
198
233
  (compilation, { normalModuleFactory }) => {
199
234
  const hooks = JavascriptModulesPlugin.getCompilationHooks(compilation);
200
235
  normalModuleFactory.hooks.createParser
201
- .for("javascript/auto")
202
- .tap("JavascriptModulesPlugin", options => {
203
- return new JavascriptParser("auto");
204
- });
236
+ .for(JAVASCRIPT_MODULE_TYPE_AUTO)
237
+ .tap(PLUGIN_NAME, options => new JavascriptParser("auto"));
205
238
  normalModuleFactory.hooks.createParser
206
- .for("javascript/dynamic")
207
- .tap("JavascriptModulesPlugin", options => {
208
- return new JavascriptParser("script");
209
- });
239
+ .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
240
+ .tap(PLUGIN_NAME, options => new JavascriptParser("script"));
210
241
  normalModuleFactory.hooks.createParser
211
- .for("javascript/esm")
212
- .tap("JavascriptModulesPlugin", options => {
213
- return new JavascriptParser("module");
214
- });
242
+ .for(JAVASCRIPT_MODULE_TYPE_ESM)
243
+ .tap(PLUGIN_NAME, options => new JavascriptParser("module"));
215
244
  normalModuleFactory.hooks.createGenerator
216
- .for("javascript/auto")
217
- .tap("JavascriptModulesPlugin", () => {
218
- return new JavascriptGenerator();
219
- });
245
+ .for(JAVASCRIPT_MODULE_TYPE_AUTO)
246
+ .tap(PLUGIN_NAME, () => new JavascriptGenerator());
220
247
  normalModuleFactory.hooks.createGenerator
221
- .for("javascript/dynamic")
222
- .tap("JavascriptModulesPlugin", () => {
223
- return new JavascriptGenerator();
224
- });
248
+ .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
249
+ .tap(PLUGIN_NAME, () => new JavascriptGenerator());
225
250
  normalModuleFactory.hooks.createGenerator
226
- .for("javascript/esm")
227
- .tap("JavascriptModulesPlugin", () => {
228
- return new JavascriptGenerator();
229
- });
230
- compilation.hooks.renderManifest.tap(
231
- "JavascriptModulesPlugin",
232
- (result, options) => {
233
- const {
234
- hash,
251
+ .for(JAVASCRIPT_MODULE_TYPE_ESM)
252
+ .tap(PLUGIN_NAME, () => new JavascriptGenerator());
253
+ compilation.hooks.renderManifest.tap(PLUGIN_NAME, (result, options) => {
254
+ const {
255
+ hash,
256
+ chunk,
257
+ chunkGraph,
258
+ moduleGraph,
259
+ runtimeTemplate,
260
+ dependencyTemplates,
261
+ outputOptions,
262
+ codeGenerationResults
263
+ } = options;
264
+
265
+ const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null;
266
+
267
+ let render;
268
+ const filenameTemplate =
269
+ JavascriptModulesPlugin.getChunkFilenameTemplate(
235
270
  chunk,
236
- chunkGraph,
237
- moduleGraph,
238
- runtimeTemplate,
239
- dependencyTemplates,
240
- outputOptions,
241
- codeGenerationResults
242
- } = options;
243
-
244
- const hotUpdateChunk =
245
- chunk instanceof HotUpdateChunk ? chunk : null;
246
-
247
- let render;
248
- const filenameTemplate =
249
- JavascriptModulesPlugin.getChunkFilenameTemplate(
250
- chunk,
251
- outputOptions
271
+ outputOptions
272
+ );
273
+ if (hotUpdateChunk) {
274
+ render = () =>
275
+ this.renderChunk(
276
+ {
277
+ chunk,
278
+ dependencyTemplates,
279
+ runtimeTemplate,
280
+ moduleGraph,
281
+ chunkGraph,
282
+ codeGenerationResults,
283
+ strictMode: runtimeTemplate.isModule()
284
+ },
285
+ hooks
252
286
  );
253
- if (hotUpdateChunk) {
254
- render = () =>
255
- this.renderChunk(
256
- {
257
- chunk,
258
- dependencyTemplates,
259
- runtimeTemplate,
260
- moduleGraph,
261
- chunkGraph,
262
- codeGenerationResults,
263
- strictMode: runtimeTemplate.isModule()
264
- },
265
- hooks
266
- );
267
- } else if (chunk.hasRuntime()) {
268
- render = () =>
269
- this.renderMain(
270
- {
271
- hash,
272
- chunk,
273
- dependencyTemplates,
274
- runtimeTemplate,
275
- moduleGraph,
276
- chunkGraph,
277
- codeGenerationResults,
278
- strictMode: runtimeTemplate.isModule()
279
- },
280
- hooks,
281
- compilation
282
- );
283
- } else {
284
- if (!chunkHasJs(chunk, chunkGraph)) {
285
- return result;
286
- }
287
-
288
- render = () =>
289
- this.renderChunk(
290
- {
291
- chunk,
292
- dependencyTemplates,
293
- runtimeTemplate,
294
- moduleGraph,
295
- chunkGraph,
296
- codeGenerationResults,
297
- strictMode: runtimeTemplate.isModule()
298
- },
299
- hooks
300
- );
287
+ } else if (chunk.hasRuntime()) {
288
+ render = () =>
289
+ this.renderMain(
290
+ {
291
+ hash,
292
+ chunk,
293
+ dependencyTemplates,
294
+ runtimeTemplate,
295
+ moduleGraph,
296
+ chunkGraph,
297
+ codeGenerationResults,
298
+ strictMode: runtimeTemplate.isModule()
299
+ },
300
+ hooks,
301
+ compilation
302
+ );
303
+ } else {
304
+ if (!chunkHasJs(chunk, chunkGraph)) {
305
+ return result;
301
306
  }
302
307
 
303
- result.push({
304
- render,
305
- filenameTemplate,
306
- pathOptions: {
307
- hash,
308
- runtime: chunk.runtime,
309
- chunk,
310
- contentHashType: "javascript"
311
- },
312
- info: {
313
- javascriptModule: compilation.runtimeTemplate.isModule()
314
- },
315
- identifier: hotUpdateChunk
316
- ? `hotupdatechunk${chunk.id}`
317
- : `chunk${chunk.id}`,
318
- hash: chunk.contentHash.javascript
319
- });
320
-
321
- return result;
322
- }
323
- );
324
- compilation.hooks.chunkHash.tap(
325
- "JavascriptModulesPlugin",
326
- (chunk, hash, context) => {
327
- hooks.chunkHash.call(chunk, hash, context);
328
- if (chunk.hasRuntime()) {
329
- this.updateHashWithBootstrap(
330
- hash,
308
+ render = () =>
309
+ this.renderChunk(
331
310
  {
332
- hash: "0000",
333
311
  chunk,
334
- chunkGraph: context.chunkGraph,
335
- moduleGraph: context.moduleGraph,
336
- runtimeTemplate: context.runtimeTemplate
312
+ dependencyTemplates,
313
+ runtimeTemplate,
314
+ moduleGraph,
315
+ chunkGraph,
316
+ codeGenerationResults,
317
+ strictMode: runtimeTemplate.isModule()
337
318
  },
338
319
  hooks
339
320
  );
340
- }
341
321
  }
342
- );
343
- compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => {
322
+
323
+ result.push({
324
+ render,
325
+ filenameTemplate,
326
+ pathOptions: {
327
+ hash,
328
+ runtime: chunk.runtime,
329
+ chunk,
330
+ contentHashType: "javascript"
331
+ },
332
+ info: {
333
+ javascriptModule: compilation.runtimeTemplate.isModule()
334
+ },
335
+ identifier: hotUpdateChunk
336
+ ? `hotupdatechunk${chunk.id}`
337
+ : `chunk${chunk.id}`,
338
+ hash: chunk.contentHash.javascript
339
+ });
340
+
341
+ return result;
342
+ });
343
+ compilation.hooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash, context) => {
344
+ hooks.chunkHash.call(chunk, hash, context);
345
+ if (chunk.hasRuntime()) {
346
+ this.updateHashWithBootstrap(
347
+ hash,
348
+ {
349
+ hash: "0000",
350
+ chunk,
351
+ codeGenerationResults: context.codeGenerationResults,
352
+ chunkGraph: context.chunkGraph,
353
+ moduleGraph: context.moduleGraph,
354
+ runtimeTemplate: context.runtimeTemplate
355
+ },
356
+ hooks
357
+ );
358
+ }
359
+ });
360
+ compilation.hooks.contentHash.tap(PLUGIN_NAME, chunk => {
344
361
  const {
345
362
  chunkGraph,
363
+ codeGenerationResults,
346
364
  moduleGraph,
347
365
  runtimeTemplate,
348
366
  outputOptions: {
@@ -360,6 +378,7 @@ class JavascriptModulesPlugin {
360
378
  {
361
379
  hash: "0000",
362
380
  chunk,
381
+ codeGenerationResults,
363
382
  chunkGraph: compilation.chunkGraph,
364
383
  moduleGraph: compilation.moduleGraph,
365
384
  runtimeTemplate: compilation.runtimeTemplate
@@ -372,6 +391,7 @@ class JavascriptModulesPlugin {
372
391
  }
373
392
  hooks.chunkHash.call(chunk, hash, {
374
393
  chunkGraph,
394
+ codeGenerationResults,
375
395
  moduleGraph,
376
396
  runtimeTemplate
377
397
  });
@@ -388,7 +408,7 @@ class JavascriptModulesPlugin {
388
408
  }
389
409
  const runtimeModules = chunkGraph.getChunkModulesIterableBySourceType(
390
410
  chunk,
391
- "runtime"
411
+ WEBPACK_MODULE_TYPE_RUNTIME
392
412
  );
393
413
  if (runtimeModules) {
394
414
  const xor = new StringXor();
@@ -398,86 +418,93 @@ class JavascriptModulesPlugin {
398
418
  xor.updateHash(hash);
399
419
  }
400
420
  const digest = /** @type {string} */ (hash.digest(hashDigest));
401
- chunk.contentHash.javascript = digest.substr(0, hashDigestLength);
421
+ chunk.contentHash.javascript = nonNumericOnlyHash(
422
+ digest,
423
+ hashDigestLength
424
+ );
402
425
  });
403
426
  compilation.hooks.additionalTreeRuntimeRequirements.tap(
404
- "JavascriptModulesPlugin",
427
+ PLUGIN_NAME,
405
428
  (chunk, set, { chunkGraph }) => {
406
429
  if (
407
430
  !set.has(RuntimeGlobals.startupNoDefault) &&
408
431
  chunkGraph.hasChunkEntryDependentChunks(chunk)
409
432
  ) {
410
433
  set.add(RuntimeGlobals.onChunksLoaded);
434
+ set.add(RuntimeGlobals.exports);
411
435
  set.add(RuntimeGlobals.require);
412
436
  }
413
437
  }
414
438
  );
415
- compilation.hooks.executeModule.tap(
416
- "JavascriptModulesPlugin",
417
- (options, context) => {
418
- const source =
419
- options.codeGenerationResult.sources.get("javascript");
420
- if (source === undefined) return;
421
- const { module, moduleObject } = options;
422
- const code = source.source();
423
-
424
- const fn = vm.runInThisContext(
425
- `(function(${module.moduleArgument}, ${module.exportsArgument}, __webpack_require__) {\n${code}\n/**/})`,
426
- {
427
- filename: module.identifier(),
428
- lineOffset: -1
429
- }
430
- );
431
- try {
432
- fn.call(
433
- moduleObject.exports,
434
- moduleObject,
435
- moduleObject.exports,
436
- context.__webpack_require__
437
- );
438
- } catch (e) {
439
- e.stack += printGeneratedCodeForStack(options.module, code);
440
- throw e;
439
+ compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
440
+ const source = options.codeGenerationResult.sources.get("javascript");
441
+ if (source === undefined) return;
442
+ const { module, moduleObject } = options;
443
+ const code = source.source();
444
+
445
+ const fn = vm.runInThisContext(
446
+ `(function(${module.moduleArgument}, ${module.exportsArgument}, ${RuntimeGlobals.require}) {\n${code}\n/**/})`,
447
+ {
448
+ filename: module.identifier(),
449
+ lineOffset: -1
441
450
  }
442
- }
443
- );
444
- compilation.hooks.executeModule.tap(
445
- "JavascriptModulesPlugin",
446
- (options, context) => {
447
- const source = options.codeGenerationResult.sources.get("runtime");
448
- if (source === undefined) return;
449
- let code = source.source();
450
- if (typeof code !== "string") code = code.toString();
451
-
452
- const fn = vm.runInThisContext(
453
- `(function(__webpack_require__) {\n${code}\n/**/})`,
454
- {
455
- filename: options.module.identifier(),
456
- lineOffset: -1
457
- }
451
+ );
452
+ try {
453
+ fn.call(
454
+ moduleObject.exports,
455
+ moduleObject,
456
+ moduleObject.exports,
457
+ context.__webpack_require__
458
458
  );
459
- try {
460
- fn.call(null, context.__webpack_require__);
461
- } catch (e) {
462
- e.stack += printGeneratedCodeForStack(options.module, code);
463
- throw e;
459
+ } catch (err) {
460
+ /** @type {Error} */
461
+ (err).stack += printGeneratedCodeForStack(
462
+ options.module,
463
+ /** @type {string} */ (code)
464
+ );
465
+ throw err;
466
+ }
467
+ });
468
+ compilation.hooks.executeModule.tap(PLUGIN_NAME, (options, context) => {
469
+ const source = options.codeGenerationResult.sources.get("runtime");
470
+ if (source === undefined) return;
471
+ let code = source.source();
472
+ if (typeof code !== "string") code = code.toString();
473
+
474
+ const fn = vm.runInThisContext(
475
+ `(function(${RuntimeGlobals.require}) {\n${code}\n/**/})`,
476
+ {
477
+ filename: options.module.identifier(),
478
+ lineOffset: -1
464
479
  }
480
+ );
481
+ try {
482
+ // eslint-disable-next-line no-useless-call
483
+ fn.call(null, context.__webpack_require__);
484
+ } catch (err) {
485
+ /** @type {Error} */
486
+ (err).stack += printGeneratedCodeForStack(options.module, code);
487
+ throw err;
465
488
  }
466
- );
489
+ });
467
490
  }
468
491
  );
469
492
  }
470
493
 
494
+ /**
495
+ * @param {Chunk} chunk chunk
496
+ * @param {OutputOptions} outputOptions output options
497
+ * @returns {TemplatePath} used filename template
498
+ */
471
499
  static getChunkFilenameTemplate(chunk, outputOptions) {
472
500
  if (chunk.filenameTemplate) {
473
501
  return chunk.filenameTemplate;
474
502
  } else if (chunk instanceof HotUpdateChunk) {
475
- return outputOptions.hotUpdateChunkFilename;
503
+ return /** @type {TemplatePath} */ (outputOptions.hotUpdateChunkFilename);
476
504
  } else if (chunk.canBeInitial()) {
477
- return outputOptions.filename;
478
- } else {
479
- return outputOptions.chunkFilename;
505
+ return /** @type {TemplatePath} */ (outputOptions.filename);
480
506
  }
507
+ return /** @type {TemplatePath} */ (outputOptions.chunkFilename);
481
508
  }
482
509
 
483
510
  /**
@@ -485,7 +512,7 @@ class JavascriptModulesPlugin {
485
512
  * @param {ChunkRenderContext} renderContext options object
486
513
  * @param {CompilationHooks} hooks hooks
487
514
  * @param {boolean} factory true: renders as factory method, false: pure module content
488
- * @returns {Source} the newly generated source from rendering
515
+ * @returns {Source | null} the newly generated source from rendering
489
516
  */
490
517
  renderModule(module, renderContext, hooks, factory) {
491
518
  const {
@@ -525,7 +552,9 @@ class JavascriptModulesPlugin {
525
552
  const needThisAsExports = runtimeRequirements.has(
526
553
  RuntimeGlobals.thisAsExports
527
554
  );
528
- const needStrict = module.buildInfo.strict && !strictMode;
555
+ const needStrict =
556
+ /** @type {BuildInfo} */
557
+ (module.buildInfo).strict && !strictMode;
529
558
  const cacheEntry = this._moduleFactoryCache.get(
530
559
  moduleSourcePostContent
531
560
  );
@@ -546,19 +575,19 @@ class JavascriptModulesPlugin {
546
575
  args.push(
547
576
  needModule
548
577
  ? module.moduleArgument
549
- : "__unused_webpack_" + module.moduleArgument
578
+ : `__unused_webpack_${module.moduleArgument}`
550
579
  );
551
580
  if (needExports || needRequire)
552
581
  args.push(
553
582
  needExports
554
583
  ? module.exportsArgument
555
- : "__unused_webpack_" + module.exportsArgument
584
+ : `__unused_webpack_${module.exportsArgument}`
556
585
  );
557
- if (needRequire) args.push("__webpack_require__");
586
+ if (needRequire) args.push(RuntimeGlobals.require);
558
587
  if (!needThisAsExports && runtimeTemplate.supportsArrowFunction()) {
559
- factorySource.add("/***/ ((" + args.join(", ") + ") => {\n\n");
588
+ factorySource.add(`/***/ ((${args.join(", ")}) => {\n\n`);
560
589
  } else {
561
- factorySource.add("/***/ (function(" + args.join(", ") + ") {\n\n");
590
+ factorySource.add(`/***/ (function(${args.join(", ")}) {\n\n`);
562
591
  }
563
592
  if (needStrict) {
564
593
  factorySource.add('"use strict";\n');
@@ -591,9 +620,9 @@ class JavascriptModulesPlugin {
591
620
  ),
592
621
  "JavascriptModulesPlugin.getCompilationHooks().renderModulePackage"
593
622
  );
594
- } catch (e) {
595
- e.module = module;
596
- throw e;
623
+ } catch (err) {
624
+ err.module = module;
625
+ throw err;
597
626
  }
598
627
  }
599
628
 
@@ -612,7 +641,10 @@ class JavascriptModulesPlugin {
612
641
  const allModules = modules ? Array.from(modules) : [];
613
642
  let strictHeader;
614
643
  let allStrict = renderContext.strictMode;
615
- if (!allStrict && allModules.every(m => m.buildInfo.strict)) {
644
+ if (
645
+ !allStrict &&
646
+ allModules.every(m => /** @type {BuildInfo} */ (m.buildInfo).strict)
647
+ ) {
616
648
  const strictBailout = hooks.strictRuntimeBailout.call(renderContext);
617
649
  strictHeader = strictBailout
618
650
  ? `// runtime can't be in strict mode because ${strictBailout}.\n`
@@ -660,8 +692,8 @@ class JavascriptModulesPlugin {
660
692
  return strictHeader
661
693
  ? new ConcatSource(strictHeader, source, ";")
662
694
  : renderContext.runtimeTemplate.isModule()
663
- ? source
664
- : new ConcatSource(source, ";");
695
+ ? source
696
+ : new ConcatSource(source, ";");
665
697
  }
666
698
 
667
699
  /**
@@ -688,12 +720,13 @@ class JavascriptModulesPlugin {
688
720
  );
689
721
 
690
722
  const hasEntryModules = chunkGraph.getNumberOfEntryModules(chunk) > 0;
723
+ /** @type {Set<Module> | undefined} */
691
724
  let inlinedModules;
692
725
  if (bootstrap.allowInlineStartup && hasEntryModules) {
693
726
  inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk));
694
727
  }
695
728
 
696
- let source = new ConcatSource();
729
+ const source = new ConcatSource();
697
730
  let prefix;
698
731
  if (iife) {
699
732
  if (runtimeTemplate.supportsArrowFunction()) {
@@ -706,16 +739,20 @@ class JavascriptModulesPlugin {
706
739
  prefix = "/******/ ";
707
740
  }
708
741
  let allStrict = renderContext.strictMode;
709
- if (!allStrict && allModules.every(m => m.buildInfo.strict)) {
742
+ if (
743
+ !allStrict &&
744
+ allModules.every(m => /** @type {BuildInfo} */ (m.buildInfo).strict)
745
+ ) {
710
746
  const strictBailout = hooks.strictRuntimeBailout.call(renderContext);
711
747
  if (strictBailout) {
712
748
  source.add(
713
- prefix +
714
- `// runtime can't be in strict mode because ${strictBailout}.\n`
749
+ `${
750
+ prefix
751
+ }// runtime can't be in strict mode because ${strictBailout}.\n`
715
752
  );
716
753
  } else {
717
754
  allStrict = true;
718
- source.add(prefix + '"use strict";\n');
755
+ source.add(`${prefix}"use strict";\n`);
719
756
  }
720
757
  }
721
758
 
@@ -729,7 +766,9 @@ class JavascriptModulesPlugin {
729
766
  const chunkModules = Template.renderChunkModules(
730
767
  chunkRenderContext,
731
768
  inlinedModules
732
- ? allModules.filter(m => !inlinedModules.has(m))
769
+ ? allModules.filter(
770
+ m => !(/** @type {Set<Module>} */ (inlinedModules).has(m))
771
+ )
733
772
  : allModules,
734
773
  module => this.renderModule(module, chunkRenderContext, hooks, true),
735
774
  prefix
@@ -740,7 +779,7 @@ class JavascriptModulesPlugin {
740
779
  runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) ||
741
780
  runtimeRequirements.has(RuntimeGlobals.require)
742
781
  ) {
743
- source.add(prefix + "var __webpack_modules__ = (");
782
+ source.add(`${prefix}var __webpack_modules__ = (`);
744
783
  source.add(chunkModules || "{}");
745
784
  source.add(");\n");
746
785
  source.add(
@@ -749,7 +788,7 @@ class JavascriptModulesPlugin {
749
788
  }
750
789
 
751
790
  if (bootstrap.header.length > 0) {
752
- const header = Template.asString(bootstrap.header) + "\n";
791
+ const header = `${Template.asString(bootstrap.header)}\n`;
753
792
  source.add(
754
793
  new PrefixSource(
755
794
  prefix,
@@ -783,7 +822,7 @@ class JavascriptModulesPlugin {
783
822
  }
784
823
  if (inlinedModules) {
785
824
  if (bootstrap.beforeStartup.length > 0) {
786
- const beforeStartup = Template.asString(bootstrap.beforeStartup) + "\n";
825
+ const beforeStartup = `${Template.asString(bootstrap.beforeStartup)}\n`;
787
826
  source.add(
788
827
  new PrefixSource(
789
828
  prefix,
@@ -793,36 +832,45 @@ class JavascriptModulesPlugin {
793
832
  )
794
833
  );
795
834
  }
796
- const lastInlinedModule = last(inlinedModules);
835
+ const lastInlinedModule = /** @type {Module} */ (last(inlinedModules));
797
836
  const startupSource = new ConcatSource();
798
- startupSource.add(`var __webpack_exports__ = {};\n`);
837
+
838
+ if (runtimeRequirements.has(RuntimeGlobals.exports)) {
839
+ startupSource.add(`var ${RuntimeGlobals.exports} = {};\n`);
840
+ }
841
+
842
+ const renamedInlinedModule = this.renameInlineModule(
843
+ allModules,
844
+ renderContext,
845
+ inlinedModules,
846
+ chunkRenderContext,
847
+ hooks
848
+ );
849
+
799
850
  for (const m of inlinedModules) {
800
- const renderedModule = this.renderModule(
801
- m,
802
- chunkRenderContext,
803
- hooks,
804
- false
805
- );
851
+ const renderedModule =
852
+ renamedInlinedModule.get(m) ||
853
+ this.renderModule(m, chunkRenderContext, hooks, false);
854
+
806
855
  if (renderedModule) {
807
- const innerStrict = !allStrict && m.buildInfo.strict;
856
+ const innerStrict =
857
+ !allStrict && /** @type {BuildInfo} */ (m.buildInfo).strict;
808
858
  const runtimeRequirements = chunkGraph.getModuleRuntimeRequirements(
809
859
  m,
810
860
  chunk.runtime
811
861
  );
812
862
  const exports = runtimeRequirements.has(RuntimeGlobals.exports);
813
863
  const webpackExports =
814
- exports && m.exportsArgument === "__webpack_exports__";
815
- let iife = innerStrict
864
+ exports && m.exportsArgument === RuntimeGlobals.exports;
865
+ const iife = innerStrict
816
866
  ? "it need to be in strict mode."
817
867
  : inlinedModules.size > 1
818
- ? // TODO check globals and top-level declarations of other entries and chunk modules
819
- // to make a better decision
820
- "it need to be isolated against other entry modules."
821
- : chunkModules
822
- ? "it need to be isolated against other modules in the chunk."
823
- : exports && !webpackExports
824
- ? `it uses a non-standard name for the exports (${m.exportsArgument}).`
825
- : hooks.embedInRuntimeBailout.call(m, renderContext);
868
+ ? // TODO check globals and top-level declarations of other entries and chunk modules
869
+ // 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);
826
874
  let footer;
827
875
  if (iife !== undefined) {
828
876
  startupSource.add(
@@ -843,9 +891,9 @@ class JavascriptModulesPlugin {
843
891
  if (exports) {
844
892
  if (m !== lastInlinedModule)
845
893
  startupSource.add(`var ${m.exportsArgument} = {};\n`);
846
- else if (m.exportsArgument !== "__webpack_exports__")
894
+ else if (m.exportsArgument !== RuntimeGlobals.exports)
847
895
  startupSource.add(
848
- `var ${m.exportsArgument} = __webpack_exports__;\n`
896
+ `var ${m.exportsArgument} = ${RuntimeGlobals.exports};\n`
849
897
  );
850
898
  }
851
899
  startupSource.add(renderedModule);
@@ -854,7 +902,7 @@ class JavascriptModulesPlugin {
854
902
  }
855
903
  if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
856
904
  startupSource.add(
857
- `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);\n`
905
+ `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});\n`
858
906
  );
859
907
  }
860
908
  source.add(
@@ -864,7 +912,7 @@ class JavascriptModulesPlugin {
864
912
  })
865
913
  );
866
914
  if (bootstrap.afterStartup.length > 0) {
867
- const afterStartup = Template.asString(bootstrap.afterStartup) + "\n";
915
+ const afterStartup = `${Template.asString(bootstrap.afterStartup)}\n`;
868
916
  source.add(
869
917
  new PrefixSource(
870
918
  prefix,
@@ -875,9 +923,10 @@ class JavascriptModulesPlugin {
875
923
  );
876
924
  }
877
925
  } else {
878
- const lastEntryModule = last(
879
- chunkGraph.getChunkEntryModulesIterable(chunk)
880
- );
926
+ const lastEntryModule =
927
+ /** @type {Module} */
928
+ (last(chunkGraph.getChunkEntryModulesIterable(chunk)));
929
+ /** @type {function(string[], string): Source} */
881
930
  const toSource = useSourceMap
882
931
  ? (content, name) =>
883
932
  new OriginalSource(Template.asString(content), name)
@@ -906,7 +955,7 @@ class JavascriptModulesPlugin {
906
955
  hasEntryModules &&
907
956
  runtimeRequirements.has(RuntimeGlobals.returnExportsFromRuntime)
908
957
  ) {
909
- source.add(`${prefix}return __webpack_exports__;\n`);
958
+ source.add(`${prefix}return ${RuntimeGlobals.exports};\n`);
910
959
  }
911
960
  if (iife) {
912
961
  source.add("/******/ })()\n");
@@ -931,6 +980,7 @@ class JavascriptModulesPlugin {
931
980
  "JavascriptModulesPlugin error: JavascriptModulesPlugin.getCompilationHooks().renderContent plugins should return something"
932
981
  );
933
982
  }
983
+
934
984
  finalSource = InitFragment.addToSource(
935
985
  finalSource,
936
986
  chunkRenderContext.chunkInitFragments,
@@ -956,7 +1006,8 @@ class JavascriptModulesPlugin {
956
1006
  */
957
1007
  updateHashWithBootstrap(hash, renderContext, hooks) {
958
1008
  const bootstrap = this.renderBootstrap(renderContext, hooks);
959
- for (const key of Object.keys(bootstrap)) {
1009
+ for (const _k of Object.keys(bootstrap)) {
1010
+ const key = /** @type {keyof Bootstrap} */ (_k);
960
1011
  hash.update(key);
961
1012
  if (Array.isArray(bootstrap[key])) {
962
1013
  for (const line of bootstrap[key]) {
@@ -971,10 +1022,16 @@ class JavascriptModulesPlugin {
971
1022
  /**
972
1023
  * @param {RenderBootstrapContext} renderContext options object
973
1024
  * @param {CompilationHooks} hooks hooks
974
- * @returns {{ header: string[], beforeStartup: string[], startup: string[], afterStartup: string[], allowInlineStartup: boolean }} the generated source of the bootstrap code
1025
+ * @returns {Bootstrap} the generated source of the bootstrap code
975
1026
  */
976
1027
  renderBootstrap(renderContext, hooks) {
977
- const { chunkGraph, moduleGraph, chunk, runtimeTemplate } = renderContext;
1028
+ const {
1029
+ chunkGraph,
1030
+ codeGenerationResults,
1031
+ moduleGraph,
1032
+ chunk,
1033
+ runtimeTemplate
1034
+ } = renderContext;
978
1035
 
979
1036
  const runtimeRequirements = chunkGraph.getTreeRuntimeRequirements(chunk);
980
1037
 
@@ -994,6 +1051,9 @@ class JavascriptModulesPlugin {
994
1051
  const useRequire =
995
1052
  requireFunction || interceptModuleExecution || moduleUsed;
996
1053
 
1054
+ /**
1055
+ * @type {{startup: string[], beforeStartup: string[], header: string[], afterStartup: string[], allowInlineStartup: boolean}}
1056
+ */
997
1057
  const result = {
998
1058
  header: [],
999
1059
  beforeStartup: [],
@@ -1002,7 +1062,7 @@ class JavascriptModulesPlugin {
1002
1062
  allowInlineStartup: true
1003
1063
  };
1004
1064
 
1005
- let { header: buf, startup, beforeStartup, afterStartup } = result;
1065
+ const { header: buf, startup, beforeStartup, afterStartup } = result;
1006
1066
 
1007
1067
  if (result.allowInlineStartup && moduleFactories) {
1008
1068
  startup.push(
@@ -1029,13 +1089,13 @@ class JavascriptModulesPlugin {
1029
1089
 
1030
1090
  if (useRequire) {
1031
1091
  buf.push("// The require function");
1032
- buf.push(`function __webpack_require__(moduleId) {`);
1092
+ buf.push(`function ${RuntimeGlobals.require}(moduleId) {`);
1033
1093
  buf.push(Template.indent(this.renderRequire(renderContext, hooks)));
1034
1094
  buf.push("}");
1035
1095
  buf.push("");
1036
1096
  } else if (runtimeRequirements.has(RuntimeGlobals.requireScope)) {
1037
1097
  buf.push("// The require scope");
1038
- buf.push("var __webpack_require__ = {};");
1098
+ buf.push(`var ${RuntimeGlobals.require} = {};`);
1039
1099
  buf.push("");
1040
1100
  }
1041
1101
 
@@ -1072,7 +1132,9 @@ class JavascriptModulesPlugin {
1072
1132
  entryModule,
1073
1133
  entrypoint
1074
1134
  ] of chunkGraph.getChunkEntryModulesWithChunkGroupIterable(chunk)) {
1075
- const chunks = entrypoint.chunks.filter(c => c !== chunk);
1135
+ const chunks =
1136
+ /** @type {Entrypoint} */
1137
+ (entrypoint).chunks.filter(c => c !== chunk);
1076
1138
  if (result.allowInlineStartup && chunks.length > 0) {
1077
1139
  buf2.push(
1078
1140
  "// This entry module depends on other loaded chunks and execution need to be delayed"
@@ -1098,8 +1160,18 @@ class JavascriptModulesPlugin {
1098
1160
  );
1099
1161
  result.allowInlineStartup = false;
1100
1162
  }
1163
+
1164
+ let data;
1165
+ if (codeGenerationResults.has(entryModule, chunk.runtime)) {
1166
+ const result = codeGenerationResults.get(
1167
+ entryModule,
1168
+ chunk.runtime
1169
+ );
1170
+ data = result.data;
1171
+ }
1101
1172
  if (
1102
1173
  result.allowInlineStartup &&
1174
+ (!data || !data.get("topLevelDeclarations")) &&
1103
1175
  (!entryModule.buildInfo ||
1104
1176
  !entryModule.buildInfo.topLevelDeclarations)
1105
1177
  ) {
@@ -1139,32 +1211,32 @@ class JavascriptModulesPlugin {
1139
1211
  }
1140
1212
  if (chunks.length > 0) {
1141
1213
  buf2.push(
1142
- `${i === 0 ? "var __webpack_exports__ = " : ""}${
1214
+ `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${
1143
1215
  RuntimeGlobals.onChunksLoaded
1144
1216
  }(undefined, ${JSON.stringify(
1145
1217
  chunks.map(c => c.id)
1146
1218
  )}, ${runtimeTemplate.returningFunction(
1147
- `__webpack_require__(${moduleIdExpr})`
1219
+ `${RuntimeGlobals.require}(${moduleIdExpr})`
1148
1220
  )})`
1149
1221
  );
1150
1222
  } else if (useRequire) {
1151
1223
  buf2.push(
1152
- `${
1153
- i === 0 ? "var __webpack_exports__ = " : ""
1154
- }__webpack_require__(${moduleIdExpr});`
1224
+ `${i === 0 ? `var ${RuntimeGlobals.exports} = ` : ""}${
1225
+ RuntimeGlobals.require
1226
+ }(${moduleIdExpr});`
1155
1227
  );
1156
1228
  } else {
1157
- if (i === 0) buf2.push("var __webpack_exports__ = {};");
1229
+ if (i === 0) buf2.push(`var ${RuntimeGlobals.exports} = {};`);
1158
1230
  if (requireScopeUsed) {
1159
1231
  buf2.push(
1160
1232
  `__webpack_modules__[${moduleIdExpr}](0, ${
1161
- i === 0 ? "__webpack_exports__" : "{}"
1162
- }, __webpack_require__);`
1233
+ i === 0 ? RuntimeGlobals.exports : "{}"
1234
+ }, ${RuntimeGlobals.require});`
1163
1235
  );
1164
1236
  } else if (entryRuntimeRequirements.has(RuntimeGlobals.exports)) {
1165
1237
  buf2.push(
1166
1238
  `__webpack_modules__[${moduleIdExpr}](0, ${
1167
- i === 0 ? "__webpack_exports__" : "{}"
1239
+ i === 0 ? RuntimeGlobals.exports : "{}"
1168
1240
  });`
1169
1241
  );
1170
1242
  } else {
@@ -1174,7 +1246,7 @@ class JavascriptModulesPlugin {
1174
1246
  }
1175
1247
  if (runtimeRequirements.has(RuntimeGlobals.onChunksLoaded)) {
1176
1248
  buf2.push(
1177
- `__webpack_exports__ = ${RuntimeGlobals.onChunksLoaded}(__webpack_exports__);`
1249
+ `${RuntimeGlobals.exports} = ${RuntimeGlobals.onChunksLoaded}(${RuntimeGlobals.exports});`
1178
1250
  );
1179
1251
  }
1180
1252
  if (
@@ -1187,13 +1259,13 @@ class JavascriptModulesPlugin {
1187
1259
  buf.push(
1188
1260
  `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction("", [
1189
1261
  ...buf2,
1190
- "return __webpack_exports__;"
1262
+ `return ${RuntimeGlobals.exports};`
1191
1263
  ])};`
1192
1264
  );
1193
1265
  buf.push("");
1194
1266
  startup.push("// run startup");
1195
1267
  startup.push(
1196
- `var __webpack_exports__ = ${RuntimeGlobals.startup}();`
1268
+ `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();`
1197
1269
  );
1198
1270
  } else if (runtimeRequirements.has(RuntimeGlobals.startupOnlyBefore)) {
1199
1271
  buf.push("// the startup function");
@@ -1241,7 +1313,9 @@ class JavascriptModulesPlugin {
1241
1313
  `${RuntimeGlobals.startup} = ${runtimeTemplate.emptyFunction()};`
1242
1314
  );
1243
1315
  startup.push("// run startup");
1244
- startup.push(`var __webpack_exports__ = ${RuntimeGlobals.startup}();`);
1316
+ startup.push(
1317
+ `var ${RuntimeGlobals.exports} = ${RuntimeGlobals.startup}();`
1318
+ );
1245
1319
  }
1246
1320
  return result;
1247
1321
  }
@@ -1262,18 +1336,18 @@ class JavascriptModulesPlugin {
1262
1336
  RuntimeGlobals.interceptModuleExecution
1263
1337
  )
1264
1338
  ? Template.asString([
1265
- "var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };",
1339
+ `var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: ${RuntimeGlobals.require} };`,
1266
1340
  `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`,
1267
1341
  "module = execOptions.module;",
1268
1342
  "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);"
1269
- ])
1343
+ ])
1270
1344
  : runtimeRequirements.has(RuntimeGlobals.thisAsExports)
1271
- ? Template.asString([
1272
- "__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);"
1273
- ])
1274
- : Template.asString([
1275
- "__webpack_modules__[moduleId](module, module.exports, __webpack_require__);"
1276
- ]);
1345
+ ? Template.asString([
1346
+ `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});`
1347
+ ])
1348
+ : Template.asString([
1349
+ `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});`
1350
+ ]);
1277
1351
  const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId);
1278
1352
  const needModuleLoaded = runtimeRequirements.has(
1279
1353
  RuntimeGlobals.moduleLoaded
@@ -1286,7 +1360,7 @@ class JavascriptModulesPlugin {
1286
1360
  ? Template.indent([
1287
1361
  "if (cachedModule.error !== undefined) throw cachedModule.error;",
1288
1362
  "return cachedModule.exports;"
1289
- ])
1363
+ ])
1290
1364
  : Template.indent("return cachedModule.exports;"),
1291
1365
  "}",
1292
1366
  "// Create a new module (and put it into the cache)",
@@ -1309,27 +1383,27 @@ class JavascriptModulesPlugin {
1309
1383
  "if(threw) delete __webpack_module_cache__[moduleId];"
1310
1384
  ]),
1311
1385
  "}"
1312
- ])
1386
+ ])
1313
1387
  : outputOptions.strictModuleErrorHandling
1314
- ? Template.asString([
1315
- "// Execute the module function",
1316
- "try {",
1317
- Template.indent(moduleExecution),
1318
- "} catch(e) {",
1319
- Template.indent(["module.error = e;", "throw e;"]),
1320
- "}"
1321
- ])
1322
- : Template.asString([
1323
- "// Execute the module function",
1324
- moduleExecution
1325
- ]),
1388
+ ? Template.asString([
1389
+ "// Execute the module function",
1390
+ "try {",
1391
+ Template.indent(moduleExecution),
1392
+ "} catch(e) {",
1393
+ Template.indent(["module.error = e;", "throw e;"]),
1394
+ "}"
1395
+ ])
1396
+ : Template.asString([
1397
+ "// Execute the module function",
1398
+ moduleExecution
1399
+ ]),
1326
1400
  needModuleLoaded
1327
1401
  ? Template.asString([
1328
1402
  "",
1329
1403
  "// Flag the module as loaded",
1330
- "module.loaded = true;",
1404
+ `${RuntimeGlobals.moduleLoaded} = true;`,
1331
1405
  ""
1332
- ])
1406
+ ])
1333
1407
  : "",
1334
1408
  "// Return the exports of the module",
1335
1409
  "return module.exports;"
@@ -1339,6 +1413,160 @@ class JavascriptModulesPlugin {
1339
1413
  "JavascriptModulesPlugin.getCompilationHooks().renderRequire"
1340
1414
  );
1341
1415
  }
1416
+
1417
+ /**
1418
+ * @param {Module[]} allModules allModules
1419
+ * @param {MainRenderContext} renderContext renderContext
1420
+ * @param {Set<Module>} inlinedModules inlinedModules
1421
+ * @param {ChunkRenderContext} chunkRenderContext chunkRenderContext
1422
+ * @param {CompilationHooks} hooks hooks
1423
+ * @returns {Map<Module, Source>} renamed inlined modules
1424
+ */
1425
+ renameInlineModule(
1426
+ allModules,
1427
+ renderContext,
1428
+ inlinedModules,
1429
+ chunkRenderContext,
1430
+ hooks
1431
+ ) {
1432
+ const { runtimeTemplate } = renderContext;
1433
+
1434
+ /** @typedef {{ source: Source, ast: any, variables: Set<Variable>, usedInNonInlined: Set<Variable>}} InlinedModulesInfo */
1435
+
1436
+ /** @type {Map<Module, InlinedModulesInfo>} */
1437
+ const inlinedModulesToInfo = new Map();
1438
+ /** @type {Set<string>} */
1439
+ const nonInlinedModuleThroughIdentifiers = new Set();
1440
+ /** @type {Map<Module, Source>} */
1441
+ const renamedInlinedModules = new Map();
1442
+
1443
+ for (const m of allModules) {
1444
+ const isInlinedModule = inlinedModules && inlinedModules.has(m);
1445
+ const moduleSource = this.renderModule(
1446
+ m,
1447
+ chunkRenderContext,
1448
+ hooks,
1449
+ !isInlinedModule
1450
+ );
1451
+
1452
+ if (!moduleSource) continue;
1453
+ const code = /** @type {string} */ (moduleSource.source());
1454
+ const ast = JavascriptParser._parse(code, {
1455
+ sourceType: "auto"
1456
+ });
1457
+
1458
+ const scopeManager = eslintScope.analyze(ast, {
1459
+ ecmaVersion: 6,
1460
+ sourceType: "module",
1461
+ optimistic: true,
1462
+ ignoreEval: true
1463
+ });
1464
+
1465
+ const globalScope = /** @type {Scope} */ (scopeManager.acquire(ast));
1466
+ if (inlinedModules && inlinedModules.has(m)) {
1467
+ const moduleScope = globalScope.childScopes[0];
1468
+ inlinedModulesToInfo.set(m, {
1469
+ source: moduleSource,
1470
+ ast,
1471
+ variables: new Set(moduleScope.variables),
1472
+ usedInNonInlined: new Set()
1473
+ });
1474
+ } else {
1475
+ for (const ref of globalScope.through) {
1476
+ nonInlinedModuleThroughIdentifiers.add(ref.identifier.name);
1477
+ }
1478
+ }
1479
+ }
1480
+
1481
+ for (const [, { variables, usedInNonInlined }] of inlinedModulesToInfo) {
1482
+ for (const variable of variables) {
1483
+ if (nonInlinedModuleThroughIdentifiers.has(variable.name)) {
1484
+ usedInNonInlined.add(variable);
1485
+ }
1486
+ }
1487
+ }
1488
+
1489
+ for (const [m, moduleInfo] of inlinedModulesToInfo) {
1490
+ const { ast, source: _source, usedInNonInlined } = moduleInfo;
1491
+ const source = new ReplaceSource(_source);
1492
+ if (usedInNonInlined.size === 0) {
1493
+ renamedInlinedModules.set(m, source);
1494
+ continue;
1495
+ }
1496
+
1497
+ const usedNames = new Set(
1498
+ Array.from(
1499
+ /** @type {InlinedModulesInfo} */
1500
+ (inlinedModulesToInfo.get(m)).variables
1501
+ ).map(v => v.name)
1502
+ );
1503
+
1504
+ for (const variable of usedInNonInlined) {
1505
+ const references = getAllReferences(variable);
1506
+ const allIdentifiers = new Set(
1507
+ references.map(r => r.identifier).concat(variable.identifiers)
1508
+ );
1509
+
1510
+ const newName = this.findNewName(
1511
+ variable.name,
1512
+ usedNames,
1513
+ m.readableIdentifier(runtimeTemplate.requestShortener)
1514
+ );
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;
1527
+ }
1528
+ }
1529
+ source.replace(r[0], r[1] - 1, newName);
1530
+ }
1531
+ }
1532
+
1533
+ renamedInlinedModules.set(m, source);
1534
+ }
1535
+
1536
+ return renamedInlinedModules;
1537
+ }
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
+ }
1342
1570
  }
1343
1571
 
1344
1572
  module.exports = JavascriptModulesPlugin;