webpack 5.59.0 → 5.71.0

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

Potentially problematic release.


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

Files changed (209) hide show
  1. package/README.md +1 -7
  2. package/hot/lazy-compilation-node.js +3 -1
  3. package/hot/poll.js +1 -1
  4. package/hot/signal.js +1 -1
  5. package/lib/APIPlugin.js +33 -0
  6. package/lib/BannerPlugin.js +10 -4
  7. package/lib/Cache.js +1 -1
  8. package/lib/CacheFacade.js +4 -11
  9. package/lib/Chunk.js +6 -3
  10. package/lib/ChunkGraph.js +1 -2
  11. package/lib/ChunkGroup.js +1 -1
  12. package/lib/CleanPlugin.js +81 -20
  13. package/lib/Compilation.js +179 -91
  14. package/lib/Compiler.js +86 -17
  15. package/lib/ConstPlugin.js +2 -2
  16. package/lib/ContextModule.js +142 -51
  17. package/lib/ContextModuleFactory.js +65 -25
  18. package/lib/DelegatedModule.js +1 -1
  19. package/lib/DelegatedModuleFactoryPlugin.js +1 -1
  20. package/lib/Dependency.js +17 -0
  21. package/lib/DependencyTemplate.js +9 -0
  22. package/lib/DependencyTemplates.js +1 -1
  23. package/lib/DllModule.js +1 -1
  24. package/lib/EntryOptionPlugin.js +2 -0
  25. package/lib/ErrorHelpers.js +2 -2
  26. package/lib/EvalDevToolModulePlugin.js +16 -1
  27. package/lib/EvalSourceMapDevToolPlugin.js +18 -1
  28. package/lib/ExportsInfo.js +4 -4
  29. package/lib/ExternalModule.js +94 -54
  30. package/lib/ExternalModuleFactoryPlugin.js +5 -5
  31. package/lib/FileSystemInfo.js +89 -44
  32. package/lib/Generator.js +3 -0
  33. package/lib/HookWebpackError.js +1 -1
  34. package/lib/HotModuleReplacementPlugin.js +3 -1
  35. package/lib/LoaderOptionsPlugin.js +1 -1
  36. package/lib/Module.js +27 -4
  37. package/lib/ModuleFilenameHelpers.js +8 -4
  38. package/lib/ModuleHashingError.js +29 -0
  39. package/lib/MultiCompiler.js +1 -1
  40. package/lib/MultiWatching.js +1 -1
  41. package/lib/NodeStuffPlugin.js +10 -0
  42. package/lib/NormalModule.js +41 -26
  43. package/lib/NormalModuleFactory.js +42 -37
  44. package/lib/ProgressPlugin.js +4 -5
  45. package/lib/RawModule.js +1 -1
  46. package/lib/RuntimeGlobals.js +29 -1
  47. package/lib/RuntimeModule.js +1 -1
  48. package/lib/RuntimePlugin.js +77 -1
  49. package/lib/RuntimeTemplate.js +114 -2
  50. package/lib/Template.js +2 -1
  51. package/lib/TemplatedPathPlugin.js +48 -23
  52. package/lib/WatchIgnorePlugin.js +19 -7
  53. package/lib/Watching.js +33 -19
  54. package/lib/WebpackOptionsApply.js +57 -11
  55. package/lib/asset/AssetGenerator.js +193 -63
  56. package/lib/asset/AssetModulesPlugin.js +3 -0
  57. package/lib/asset/RawDataUrlModule.js +148 -0
  58. package/lib/async-modules/AwaitDependenciesInitFragment.js +4 -4
  59. package/lib/buildChunkGraph.js +36 -6
  60. package/lib/cache/PackFileCacheStrategy.js +7 -4
  61. package/lib/cache/ResolverCachePlugin.js +90 -29
  62. package/lib/cli.js +44 -3
  63. package/lib/config/browserslistTargetHandler.js +41 -6
  64. package/lib/config/defaults.js +115 -19
  65. package/lib/config/normalization.js +9 -0
  66. package/lib/config/target.js +10 -0
  67. package/lib/container/ContainerEntryModule.js +8 -5
  68. package/lib/container/FallbackModule.js +4 -4
  69. package/lib/container/RemoteModule.js +4 -2
  70. package/lib/css/CssExportsGenerator.js +139 -0
  71. package/lib/css/CssGenerator.js +109 -0
  72. package/lib/css/CssLoadingRuntimeModule.js +440 -0
  73. package/lib/css/CssModulesPlugin.js +462 -0
  74. package/lib/css/CssParser.js +618 -0
  75. package/lib/css/walkCssTokens.js +659 -0
  76. package/lib/debug/ProfilingPlugin.js +24 -21
  77. package/lib/dependencies/AMDRequireDependency.js +6 -6
  78. package/lib/dependencies/CommonJsExportsParserPlugin.js +1 -2
  79. package/lib/dependencies/CommonJsFullRequireDependency.js +5 -1
  80. package/lib/dependencies/CommonJsImportsParserPlugin.js +5 -3
  81. package/lib/dependencies/CommonJsRequireContextDependency.js +5 -1
  82. package/lib/dependencies/ContextDependency.js +1 -0
  83. package/lib/dependencies/ContextDependencyHelpers.js +3 -3
  84. package/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +4 -1
  85. package/lib/dependencies/ContextElementDependency.js +41 -3
  86. package/lib/dependencies/CreateScriptUrlDependency.js +12 -0
  87. package/lib/dependencies/CssExportDependency.js +85 -0
  88. package/lib/dependencies/CssImportDependency.js +75 -0
  89. package/lib/dependencies/CssLocalIdentifierDependency.js +119 -0
  90. package/lib/dependencies/CssSelfLocalIdentifierDependency.js +101 -0
  91. package/lib/dependencies/CssUrlDependency.js +132 -0
  92. package/lib/dependencies/ExportsInfoDependency.js +6 -0
  93. package/lib/dependencies/HarmonyAcceptImportDependency.js +5 -3
  94. package/lib/dependencies/HarmonyCompatibilityDependency.js +5 -5
  95. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +95 -0
  96. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +12 -3
  97. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +25 -17
  98. package/lib/dependencies/HarmonyExportInitFragment.js +4 -1
  99. package/lib/dependencies/HarmonyImportDependency.js +23 -0
  100. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +142 -45
  101. package/lib/dependencies/HarmonyImportSpecifierDependency.js +46 -22
  102. package/lib/dependencies/HarmonyModulesPlugin.js +10 -0
  103. package/lib/dependencies/ImportContextDependency.js +0 -2
  104. package/lib/dependencies/ImportMetaContextDependency.js +35 -0
  105. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +252 -0
  106. package/lib/dependencies/ImportMetaContextPlugin.js +59 -0
  107. package/lib/dependencies/ImportMetaPlugin.js +22 -3
  108. package/lib/dependencies/LoaderPlugin.js +4 -2
  109. package/lib/dependencies/RequireContextDependency.js +0 -16
  110. package/lib/dependencies/RequireEnsureDependency.js +2 -2
  111. package/lib/dependencies/URLDependency.js +3 -8
  112. package/lib/dependencies/URLPlugin.js +1 -1
  113. package/lib/esm/ModuleChunkFormatPlugin.js +74 -49
  114. package/lib/esm/ModuleChunkLoadingPlugin.js +3 -1
  115. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +25 -9
  116. package/lib/hmr/HotModuleReplacement.runtime.js +29 -14
  117. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +4 -3
  118. package/lib/hmr/LazyCompilationPlugin.js +54 -26
  119. package/lib/hmr/lazyCompilationBackend.js +51 -12
  120. package/lib/ids/DeterministicModuleIdsPlugin.js +55 -35
  121. package/lib/ids/HashedModuleIdsPlugin.js +11 -14
  122. package/lib/ids/IdHelpers.js +25 -11
  123. package/lib/ids/NamedModuleIdsPlugin.js +6 -9
  124. package/lib/ids/NaturalModuleIdsPlugin.js +10 -13
  125. package/lib/ids/OccurrenceModuleIdsPlugin.js +13 -10
  126. package/lib/ids/SyncModuleIdsPlugin.js +140 -0
  127. package/lib/index.js +13 -0
  128. package/lib/javascript/ArrayPushCallbackChunkFormatPlugin.js +2 -2
  129. package/lib/javascript/BasicEvaluatedExpression.js +5 -2
  130. package/lib/javascript/ChunkHelpers.js +33 -0
  131. package/lib/javascript/JavascriptGenerator.js +1 -0
  132. package/lib/javascript/JavascriptModulesPlugin.js +27 -2
  133. package/lib/javascript/JavascriptParser.js +82 -48
  134. package/lib/javascript/StartupHelpers.js +7 -30
  135. package/lib/library/AssignLibraryPlugin.js +39 -15
  136. package/lib/library/EnableLibraryPlugin.js +11 -0
  137. package/lib/library/UmdLibraryPlugin.js +5 -3
  138. package/lib/node/NodeTargetPlugin.js +3 -0
  139. package/lib/node/NodeWatchFileSystem.js +85 -31
  140. package/lib/node/ReadFileChunkLoadingRuntimeModule.js +23 -8
  141. package/lib/node/RequireChunkLoadingRuntimeModule.js +24 -9
  142. package/lib/optimize/ConcatenatedModule.js +21 -9
  143. package/lib/optimize/ModuleConcatenationPlugin.js +5 -2
  144. package/lib/optimize/SplitChunksPlugin.js +8 -1
  145. package/lib/runtime/AsyncModuleRuntimeModule.js +27 -17
  146. package/lib/runtime/BaseUriRuntimeModule.js +31 -0
  147. package/lib/runtime/CreateScriptRuntimeModule.js +36 -0
  148. package/lib/runtime/CreateScriptUrlRuntimeModule.js +9 -34
  149. package/lib/runtime/GetTrustedTypesPolicyRuntimeModule.js +76 -0
  150. package/lib/schemes/HttpUriPlugin.js +77 -14
  151. package/lib/serialization/FileMiddleware.js +44 -9
  152. package/lib/sharing/ConsumeSharedModule.js +8 -2
  153. package/lib/sharing/ConsumeSharedRuntimeModule.js +26 -5
  154. package/lib/sharing/ProvideSharedModule.js +4 -2
  155. package/lib/sharing/ShareRuntimeModule.js +1 -1
  156. package/lib/sharing/utils.js +1 -1
  157. package/lib/stats/DefaultStatsFactoryPlugin.js +113 -68
  158. package/lib/stats/DefaultStatsPrinterPlugin.js +89 -24
  159. package/lib/util/ArrayHelpers.js +30 -0
  160. package/lib/util/AsyncQueue.js +1 -1
  161. package/lib/util/compileBooleanMatcher.js +1 -1
  162. package/lib/util/create-schema-validation.js +9 -2
  163. package/lib/util/createHash.js +12 -0
  164. package/lib/util/deprecation.js +10 -2
  165. package/lib/util/deterministicGrouping.js +1 -1
  166. package/lib/util/extractUrlAndGlobal.js +3 -0
  167. package/lib/util/fs.js +11 -0
  168. package/lib/util/hash/BatchedHash.js +7 -4
  169. package/lib/util/hash/md4.js +20 -0
  170. package/lib/util/hash/wasm-hash.js +163 -0
  171. package/lib/util/hash/xxhash64.js +5 -139
  172. package/lib/util/identifier.js +65 -44
  173. package/lib/util/internalSerializables.js +15 -0
  174. package/lib/util/nonNumericOnlyHash.js +22 -0
  175. package/lib/util/semver.js +17 -10
  176. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +9 -3
  177. package/lib/web/JsonpChunkLoadingRuntimeModule.js +20 -9
  178. package/lib/webpack.js +10 -3
  179. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -11
  180. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +33 -22
  181. package/module.d.ts +215 -0
  182. package/package.json +23 -28
  183. package/schemas/WebpackOptions.check.js +1 -1
  184. package/schemas/WebpackOptions.json +254 -29
  185. package/schemas/plugins/DllReferencePlugin.check.js +1 -1
  186. package/schemas/plugins/HashedModuleIdsPlugin.check.js +1 -1
  187. package/schemas/plugins/ProgressPlugin.check.js +1 -1
  188. package/schemas/plugins/asset/AssetGeneratorOptions.check.js +1 -1
  189. package/schemas/plugins/asset/AssetParserOptions.check.js +1 -1
  190. package/schemas/plugins/asset/AssetResourceGeneratorOptions.check.js +1 -1
  191. package/schemas/plugins/container/ContainerPlugin.check.js +1 -1
  192. package/schemas/plugins/container/ContainerPlugin.json +2 -1
  193. package/schemas/plugins/container/ContainerReferencePlugin.check.js +1 -1
  194. package/schemas/plugins/container/ContainerReferencePlugin.json +1 -0
  195. package/schemas/plugins/container/ExternalsType.check.js +1 -1
  196. package/schemas/plugins/container/ModuleFederationPlugin.check.js +1 -1
  197. package/schemas/plugins/container/ModuleFederationPlugin.json +3 -1
  198. package/schemas/plugins/css/CssGeneratorOptions.check.d.ts +7 -0
  199. package/schemas/plugins/css/CssGeneratorOptions.check.js +6 -0
  200. package/schemas/plugins/css/CssGeneratorOptions.json +3 -0
  201. package/schemas/plugins/css/CssParserOptions.check.d.ts +7 -0
  202. package/schemas/plugins/css/CssParserOptions.check.js +6 -0
  203. package/schemas/plugins/css/CssParserOptions.json +3 -0
  204. package/schemas/plugins/optimize/AggressiveSplittingPlugin.check.js +1 -1
  205. package/schemas/plugins/optimize/LimitChunkCountPlugin.check.js +1 -1
  206. package/schemas/plugins/optimize/MinChunkSizePlugin.check.js +1 -1
  207. package/schemas/plugins/schemes/HttpUriPlugin.check.js +1 -1
  208. package/schemas/plugins/schemes/HttpUriPlugin.json +4 -0
  209. package/types.d.ts +628 -179
@@ -0,0 +1,252 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Ivan Kopeykin @vankop
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const WebpackError = require("../WebpackError");
9
+ const {
10
+ evaluateToIdentifier
11
+ } = require("../javascript/JavascriptParserHelpers");
12
+ const ImportMetaContextDependency = require("./ImportMetaContextDependency");
13
+
14
+ /** @typedef {import("estree").Expression} ExpressionNode */
15
+ /** @typedef {import("estree").ObjectExpression} ObjectExpressionNode */
16
+ /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
17
+ /** @typedef {import("../ContextModule").ContextModuleOptions} ContextModuleOptions */
18
+ /** @typedef {import("../ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
19
+ /** @typedef {Pick<ContextModuleOptions, 'mode'|'recursive'|'regExp'|'include'|'exclude'|'chunkName'>&{groupOptions: RawChunkGroupOptions, exports?: ContextModuleOptions["referencedExports"]}} ImportMetaContextOptions */
20
+
21
+ function createPropertyParseError(prop, expect) {
22
+ return createError(
23
+ `Parsing import.meta.webpackContext options failed. Unknown value for property ${JSON.stringify(
24
+ prop.key.name
25
+ )}, expected type ${expect}.`,
26
+ prop.value.loc
27
+ );
28
+ }
29
+
30
+ function createError(msg, loc) {
31
+ const error = new WebpackError(msg);
32
+ error.name = "ImportMetaContextError";
33
+ error.loc = loc;
34
+ return error;
35
+ }
36
+
37
+ module.exports = class ImportMetaContextDependencyParserPlugin {
38
+ apply(parser) {
39
+ parser.hooks.evaluateIdentifier
40
+ .for("import.meta.webpackContext")
41
+ .tap("HotModuleReplacementPlugin", expr => {
42
+ return evaluateToIdentifier(
43
+ "import.meta.webpackContext",
44
+ "import.meta",
45
+ () => ["webpackContext"],
46
+ true
47
+ )(expr);
48
+ });
49
+ parser.hooks.call
50
+ .for("import.meta.webpackContext")
51
+ .tap("ImportMetaContextDependencyParserPlugin", expr => {
52
+ if (expr.arguments.length < 1 || expr.arguments.length > 2) return;
53
+ const [directoryNode, optionsNode] = expr.arguments;
54
+ if (optionsNode && optionsNode.type !== "ObjectExpression") return;
55
+ const requestExpr = parser.evaluateExpression(directoryNode);
56
+ if (!requestExpr.isString()) return;
57
+ const request = requestExpr.string;
58
+ const errors = [];
59
+ let regExp = /^\.\/.*$/;
60
+ let recursive = true;
61
+ /** @type {ContextModuleOptions["mode"]} */
62
+ let mode = "sync";
63
+ /** @type {ContextModuleOptions["include"]} */
64
+ let include;
65
+ /** @type {ContextModuleOptions["exclude"]} */
66
+ let exclude;
67
+ /** @type {RawChunkGroupOptions} */
68
+ const groupOptions = {};
69
+ /** @type {ContextModuleOptions["chunkName"]} */
70
+ let chunkName;
71
+ /** @type {ContextModuleOptions["referencedExports"]} */
72
+ let exports;
73
+ if (optionsNode) {
74
+ for (const prop of optionsNode.properties) {
75
+ if (prop.type !== "Property" || prop.key.type !== "Identifier") {
76
+ errors.push(
77
+ createError(
78
+ "Parsing import.meta.webpackContext options failed.",
79
+ optionsNode.loc
80
+ )
81
+ );
82
+ break;
83
+ }
84
+ switch (prop.key.name) {
85
+ case "regExp": {
86
+ const regExpExpr = parser.evaluateExpression(
87
+ /** @type {ExpressionNode} */ (prop.value)
88
+ );
89
+ if (!regExpExpr.isRegExp()) {
90
+ errors.push(createPropertyParseError(prop, "RegExp"));
91
+ } else {
92
+ regExp = regExpExpr.regExp;
93
+ }
94
+ break;
95
+ }
96
+ case "include": {
97
+ const regExpExpr = parser.evaluateExpression(
98
+ /** @type {ExpressionNode} */ (prop.value)
99
+ );
100
+ if (!regExpExpr.isRegExp()) {
101
+ errors.push(createPropertyParseError(prop, "RegExp"));
102
+ } else {
103
+ include = regExpExpr.regExp;
104
+ }
105
+ break;
106
+ }
107
+ case "exclude": {
108
+ const regExpExpr = parser.evaluateExpression(
109
+ /** @type {ExpressionNode} */ (prop.value)
110
+ );
111
+ if (!regExpExpr.isRegExp()) {
112
+ errors.push(createPropertyParseError(prop, "RegExp"));
113
+ } else {
114
+ exclude = regExpExpr.regExp;
115
+ }
116
+ break;
117
+ }
118
+ case "mode": {
119
+ const modeExpr = parser.evaluateExpression(
120
+ /** @type {ExpressionNode} */ (prop.value)
121
+ );
122
+ if (!modeExpr.isString()) {
123
+ errors.push(createPropertyParseError(prop, "string"));
124
+ } else {
125
+ mode = /** @type {ContextModuleOptions["mode"]} */ (
126
+ modeExpr.string
127
+ );
128
+ }
129
+ break;
130
+ }
131
+ case "chunkName": {
132
+ const expr = parser.evaluateExpression(
133
+ /** @type {ExpressionNode} */ (prop.value)
134
+ );
135
+ if (!expr.isString()) {
136
+ errors.push(createPropertyParseError(prop, "string"));
137
+ } else {
138
+ chunkName = expr.string;
139
+ }
140
+ break;
141
+ }
142
+ case "exports": {
143
+ const expr = parser.evaluateExpression(
144
+ /** @type {ExpressionNode} */ (prop.value)
145
+ );
146
+ if (expr.isString()) {
147
+ exports = [[expr.string]];
148
+ } else if (expr.isArray()) {
149
+ const items = expr.items;
150
+ if (
151
+ items.every(i => {
152
+ if (!i.isArray()) return false;
153
+ const innerItems = i.items;
154
+ return innerItems.every(i => i.isString());
155
+ })
156
+ ) {
157
+ exports = [];
158
+ for (const i1 of items) {
159
+ const export_ = [];
160
+ for (const i2 of i1.items) {
161
+ export_.push(i2.string);
162
+ }
163
+ exports.push(export_);
164
+ }
165
+ } else {
166
+ errors.push(
167
+ createPropertyParseError(prop, "string|string[][]")
168
+ );
169
+ }
170
+ } else {
171
+ errors.push(
172
+ createPropertyParseError(prop, "string|string[][]")
173
+ );
174
+ }
175
+ break;
176
+ }
177
+ case "prefetch": {
178
+ const expr = parser.evaluateExpression(
179
+ /** @type {ExpressionNode} */ (prop.value)
180
+ );
181
+ if (expr.isBoolean()) {
182
+ groupOptions.prefetchOrder = 0;
183
+ } else if (expr.isNumber()) {
184
+ groupOptions.prefetchOrder = expr.number;
185
+ } else {
186
+ errors.push(createPropertyParseError(prop, "boolean|number"));
187
+ }
188
+ break;
189
+ }
190
+ case "preload": {
191
+ const expr = parser.evaluateExpression(
192
+ /** @type {ExpressionNode} */ (prop.value)
193
+ );
194
+ if (expr.isBoolean()) {
195
+ groupOptions.preloadOrder = 0;
196
+ } else if (expr.isNumber()) {
197
+ groupOptions.preloadOrder = expr.number;
198
+ } else {
199
+ errors.push(createPropertyParseError(prop, "boolean|number"));
200
+ }
201
+ break;
202
+ }
203
+ case "recursive": {
204
+ const recursiveExpr = parser.evaluateExpression(
205
+ /** @type {ExpressionNode} */ (prop.value)
206
+ );
207
+ if (!recursiveExpr.isBoolean()) {
208
+ errors.push(createPropertyParseError(prop, "boolean"));
209
+ } else {
210
+ recursive = recursiveExpr.bool;
211
+ }
212
+ break;
213
+ }
214
+ default:
215
+ errors.push(
216
+ createError(
217
+ `Parsing import.meta.webpackContext options failed. Unknown property ${JSON.stringify(
218
+ prop.key.name
219
+ )}.`,
220
+ optionsNode.loc
221
+ )
222
+ );
223
+ }
224
+ }
225
+ }
226
+ if (errors.length) {
227
+ for (const error of errors) parser.state.current.addError(error);
228
+ return;
229
+ }
230
+
231
+ const dep = new ImportMetaContextDependency(
232
+ {
233
+ request,
234
+ include,
235
+ exclude,
236
+ recursive,
237
+ regExp,
238
+ groupOptions,
239
+ chunkName,
240
+ referencedExports: exports,
241
+ mode,
242
+ category: "esm"
243
+ },
244
+ expr.range
245
+ );
246
+ dep.loc = expr.loc;
247
+ dep.optional = !!parser.scope.inTry;
248
+ parser.state.current.addDependency(dep);
249
+ return true;
250
+ });
251
+ }
252
+ };
@@ -0,0 +1,59 @@
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Ivan Kopeykin @vankop
4
+ */
5
+
6
+ "use strict";
7
+
8
+ const ContextElementDependency = require("./ContextElementDependency");
9
+ const ImportMetaContextDependency = require("./ImportMetaContextDependency");
10
+ const ImportMetaContextDependencyParserPlugin = require("./ImportMetaContextDependencyParserPlugin");
11
+
12
+ /** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
13
+ /** @typedef {import("../Compiler")} Compiler */
14
+
15
+ class ImportMetaContextPlugin {
16
+ /**
17
+ * Apply the plugin
18
+ * @param {Compiler} compiler the compiler instance
19
+ * @returns {void}
20
+ */
21
+ apply(compiler) {
22
+ compiler.hooks.compilation.tap(
23
+ "RequireContextPlugin",
24
+ (compilation, { contextModuleFactory, normalModuleFactory }) => {
25
+ compilation.dependencyFactories.set(
26
+ ImportMetaContextDependency,
27
+ contextModuleFactory
28
+ );
29
+ compilation.dependencyTemplates.set(
30
+ ImportMetaContextDependency,
31
+ new ImportMetaContextDependency.Template()
32
+ );
33
+ compilation.dependencyFactories.set(
34
+ ContextElementDependency,
35
+ normalModuleFactory
36
+ );
37
+
38
+ const handler = (parser, parserOptions) => {
39
+ if (
40
+ parserOptions.importMetaContext !== undefined &&
41
+ !parserOptions.importMetaContext
42
+ )
43
+ return;
44
+
45
+ new ImportMetaContextDependencyParserPlugin().apply(parser);
46
+ };
47
+
48
+ normalModuleFactory.hooks.parser
49
+ .for("javascript/auto")
50
+ .tap("ImportMetaContextPlugin", handler);
51
+ normalModuleFactory.hooks.parser
52
+ .for("javascript/esm")
53
+ .tap("ImportMetaContextPlugin", handler);
54
+ }
55
+ );
56
+ }
57
+ }
58
+
59
+ module.exports = ImportMetaContextPlugin;
@@ -20,6 +20,7 @@ const propertyAccess = require("../util/propertyAccess");
20
20
  const ConstDependency = require("./ConstDependency");
21
21
 
22
22
  /** @typedef {import("estree").MemberExpression} MemberExpression */
23
+ /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
23
24
  /** @typedef {import("../Compiler")} Compiler */
24
25
  /** @typedef {import("../NormalModule")} NormalModule */
25
26
  /** @typedef {import("../javascript/JavascriptParser")} Parser */
@@ -44,11 +45,29 @@ class ImportMetaPlugin {
44
45
  return pathToFileURL(module.resource).toString();
45
46
  };
46
47
  /**
47
- * @param {Parser} parser parser
48
- * @param {Object} parserOptions parserOptions
48
+ * @param {Parser} parser parser parser
49
+ * @param {JavascriptParserOptions} parserOptions parserOptions
49
50
  * @returns {void}
50
51
  */
51
- const parserHandler = (parser, parserOptions) => {
52
+ const parserHandler = (parser, { importMeta }) => {
53
+ if (importMeta === false) {
54
+ const { importMetaName } = compilation.outputOptions;
55
+ if (importMetaName === "import.meta") return;
56
+
57
+ parser.hooks.expression
58
+ .for("import.meta")
59
+ .tap("ImportMetaPlugin", metaProperty => {
60
+ const dep = new ConstDependency(
61
+ importMetaName,
62
+ metaProperty.range
63
+ );
64
+ dep.loc = metaProperty.loc;
65
+ parser.state.module.addPresentationalDependency(dep);
66
+ return true;
67
+ });
68
+ return;
69
+ }
70
+
52
71
  /// import.meta direct ///
53
72
  parser.hooks.typeof
54
73
  .for("import.meta")
@@ -16,7 +16,7 @@ const LoaderImportDependency = require("./LoaderImportDependency");
16
16
 
17
17
  /**
18
18
  * @callback LoadModuleCallback
19
- * @param {Error=} err error object
19
+ * @param {(Error | null)=} err error object
20
20
  * @param {string | Buffer=} source source code
21
21
  * @param {object=} map source map
22
22
  * @param {Module=} module loaded module if successful
@@ -24,7 +24,7 @@ const LoaderImportDependency = require("./LoaderImportDependency");
24
24
 
25
25
  /**
26
26
  * @callback ImportModuleCallback
27
- * @param {Error=} err error object
27
+ * @param {(Error | null)=} err error object
28
28
  * @param {any=} exports exports of the evaluated module
29
29
  */
30
30
 
@@ -32,6 +32,7 @@ const LoaderImportDependency = require("./LoaderImportDependency");
32
32
  * @typedef {Object} ImportModuleOptions
33
33
  * @property {string=} layer the target layer
34
34
  * @property {string=} publicPath the target public path
35
+ * @property {string=} baseUri target base uri
35
36
  */
36
37
 
37
38
  class LoaderPlugin {
@@ -199,6 +200,7 @@ class LoaderPlugin {
199
200
  referencedModule,
200
201
  {
201
202
  entryOptions: {
203
+ baseUri: options.baseUri,
202
204
  publicPath: options.publicPath
203
205
  }
204
206
  },
@@ -19,22 +19,6 @@ class RequireContextDependency extends ContextDependency {
19
19
  get type() {
20
20
  return "require.context";
21
21
  }
22
-
23
- serialize(context) {
24
- const { write } = context;
25
-
26
- write(this.range);
27
-
28
- super.serialize(context);
29
- }
30
-
31
- deserialize(context) {
32
- const { read } = context;
33
-
34
- this.range = read();
35
-
36
- super.deserialize(context);
37
- }
38
22
  }
39
23
 
40
24
  makeSerializable(
@@ -85,14 +85,14 @@ RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate extends
85
85
  source.replace(
86
86
  contentRange[1],
87
87
  errorHandlerRange[0] - 1,
88
- ").bind(null, __webpack_require__)).catch("
88
+ ").bind(null, __webpack_require__))['catch']("
89
89
  );
90
90
  source.replace(errorHandlerRange[1], range[1] - 1, ")");
91
91
  } else {
92
92
  source.replace(
93
93
  contentRange[1],
94
94
  range[1] - 1,
95
- `).bind(null, __webpack_require__)).catch(${RuntimeGlobals.uncaughtErrorHandler})`
95
+ `).bind(null, __webpack_require__))['catch'](${RuntimeGlobals.uncaughtErrorHandler})`
96
96
  );
97
97
  }
98
98
  }
@@ -25,7 +25,7 @@ const ModuleDependency = require("./ModuleDependency");
25
25
  /** @typedef {import("../util/Hash")} Hash */
26
26
  /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
27
27
 
28
- const getRawModule = memoize(() => require("../RawModule"));
28
+ const getRawDataUrlModule = memoize(() => require("../asset/RawDataUrlModule"));
29
29
 
30
30
  class URLDependency extends ModuleDependency {
31
31
  /**
@@ -68,13 +68,8 @@ class URLDependency extends ModuleDependency {
68
68
  * @returns {Module} a module
69
69
  */
70
70
  createIgnoredModule(context) {
71
- const RawModule = getRawModule();
72
- return new RawModule(
73
- 'module.exports = "data:,";',
74
- `ignored-asset`,
75
- `(ignored asset)`,
76
- new Set([RuntimeGlobals.module])
77
- );
71
+ const RawDataUrlModule = getRawDataUrlModule();
72
+ return new RawDataUrlModule("data:,", `ignored-asset`, `(ignored asset)`);
78
73
  }
79
74
 
80
75
  serialize(context) {
@@ -82,7 +82,7 @@ class URLPlugin {
82
82
  relative
83
83
  );
84
84
  dep.loc = expr.loc;
85
- parser.state.module.addDependency(dep);
85
+ parser.state.current.addDependency(dep);
86
86
  InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
87
87
  return true;
88
88
  });
@@ -5,18 +5,16 @@
5
5
 
6
6
  "use strict";
7
7
 
8
- const { ConcatSource, RawSource } = require("webpack-sources");
8
+ const { ConcatSource } = require("webpack-sources");
9
9
  const { RuntimeGlobals } = require("..");
10
10
  const HotUpdateChunk = require("../HotUpdateChunk");
11
11
  const Template = require("../Template");
12
+ const { getAllChunks } = require("../javascript/ChunkHelpers");
12
13
  const {
13
14
  getCompilationHooks,
14
15
  getChunkFilenameTemplate
15
16
  } = require("../javascript/JavascriptModulesPlugin");
16
- const {
17
- generateEntryStartup,
18
- updateHashForEntryStartup
19
- } = require("../javascript/StartupHelpers");
17
+ const { updateHashForEntryStartup } = require("../javascript/StartupHelpers");
20
18
 
21
19
  /** @typedef {import("../Compiler")} Compiler */
22
20
 
@@ -84,63 +82,90 @@ class ModuleChunkFormatPlugin {
84
82
  }
85
83
  )
86
84
  .split("/");
87
- const runtimeOutputName = compilation
88
- .getPath(
89
- getChunkFilenameTemplate(
90
- runtimeChunk,
91
- compilation.outputOptions
92
- ),
93
- {
94
- chunk: runtimeChunk,
95
- contentHashType: "javascript"
96
- }
97
- )
98
- .split("/");
99
85
 
100
86
  // remove filename, we only need the directory
101
- const outputFilename = currentOutputName.pop();
87
+ currentOutputName.pop();
102
88
 
103
- // remove common parts
104
- while (
105
- currentOutputName.length > 0 &&
106
- runtimeOutputName.length > 0 &&
107
- currentOutputName[0] === runtimeOutputName[0]
108
- ) {
109
- currentOutputName.shift();
110
- runtimeOutputName.shift();
111
- }
89
+ const getRelativePath = chunk => {
90
+ const baseOutputName = currentOutputName.slice();
91
+ const chunkOutputName = compilation
92
+ .getPath(
93
+ getChunkFilenameTemplate(
94
+ chunk,
95
+ compilation.outputOptions
96
+ ),
97
+ {
98
+ chunk: chunk,
99
+ contentHashType: "javascript"
100
+ }
101
+ )
102
+ .split("/");
112
103
 
113
- // create final path
114
- const runtimePath =
115
- (currentOutputName.length > 0
116
- ? "../".repeat(currentOutputName.length)
117
- : "./") + runtimeOutputName.join("/");
104
+ // remove common parts
105
+ while (
106
+ baseOutputName.length > 0 &&
107
+ chunkOutputName.length > 0 &&
108
+ baseOutputName[0] === chunkOutputName[0]
109
+ ) {
110
+ baseOutputName.shift();
111
+ chunkOutputName.shift();
112
+ }
113
+ // create final path
114
+ return (
115
+ (baseOutputName.length > 0
116
+ ? "../".repeat(baseOutputName.length)
117
+ : "./") + chunkOutputName.join("/")
118
+ );
119
+ };
118
120
 
119
121
  const entrySource = new ConcatSource();
120
122
  entrySource.add(source);
121
123
  entrySource.add(";\n\n// load runtime\n");
122
124
  entrySource.add(
123
125
  `import __webpack_require__ from ${JSON.stringify(
124
- runtimePath
125
- )};\n`
126
- );
127
- entrySource.add(
128
- `import * as __webpack_self_exports__ from ${JSON.stringify(
129
- "./" + outputFilename
126
+ getRelativePath(runtimeChunk)
130
127
  )};\n`
131
128
  );
132
- entrySource.add(
133
- `${RuntimeGlobals.externalInstallChunk}(__webpack_self_exports__);\n`
134
- );
135
- const startupSource = new RawSource(
136
- generateEntryStartup(
137
- chunkGraph,
138
- runtimeTemplate,
139
- entries,
140
- chunk,
141
- false
142
- )
129
+
130
+ const startupSource = new ConcatSource();
131
+ startupSource.add(
132
+ `var __webpack_exec__ = ${runtimeTemplate.returningFunction(
133
+ `__webpack_require__(${RuntimeGlobals.entryModuleId} = moduleId)`,
134
+ "moduleId"
135
+ )}\n`
143
136
  );
137
+
138
+ const loadedChunks = new Set();
139
+ let index = 0;
140
+ for (let i = 0; i < entries.length; i++) {
141
+ const [module, entrypoint] = entries[i];
142
+ const final = i + 1 === entries.length;
143
+ const moduleId = chunkGraph.getModuleId(module);
144
+ const chunks = getAllChunks(
145
+ entrypoint,
146
+ runtimeChunk,
147
+ undefined
148
+ );
149
+ for (const chunk of chunks) {
150
+ if (loadedChunks.has(chunk)) continue;
151
+ loadedChunks.add(chunk);
152
+ startupSource.add(
153
+ `import * as __webpack_chunk_${index}__ from ${JSON.stringify(
154
+ getRelativePath(chunk)
155
+ )};\n`
156
+ );
157
+ startupSource.add(
158
+ `${RuntimeGlobals.externalInstallChunk}(__webpack_chunk_${index}__);\n`
159
+ );
160
+ index++;
161
+ }
162
+ startupSource.add(
163
+ `${
164
+ final ? "var __webpack_exports__ = " : ""
165
+ }__webpack_exec__(${JSON.stringify(moduleId)});\n`
166
+ );
167
+ }
168
+
144
169
  entrySource.add(
145
170
  hooks.renderStartup.call(
146
171
  startupSource,
@@ -25,7 +25,9 @@ class ModuleChunkLoadingPlugin {
25
25
  const isEnabledForChunk = chunk => {
26
26
  const options = chunk.getEntryOptions();
27
27
  const chunkLoading =
28
- (options && options.chunkLoading) || globalChunkLoading;
28
+ options && options.chunkLoading !== undefined
29
+ ? options.chunkLoading
30
+ : globalChunkLoading;
29
31
  return chunkLoading === "import";
30
32
  };
31
33
  const onceForChunkSet = new WeakSet();
@@ -55,15 +55,35 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
55
55
  this._runtimeRequirements = runtimeRequirements;
56
56
  }
57
57
 
58
+ /**
59
+ * @private
60
+ * @param {Chunk} chunk chunk
61
+ * @param {string} rootOutputDir root output directory
62
+ * @returns {string} generated code
63
+ */
64
+ _generateBaseUri(chunk, rootOutputDir) {
65
+ const options = chunk.getEntryOptions();
66
+ if (options && options.baseUri) {
67
+ return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
68
+ }
69
+ const {
70
+ compilation: {
71
+ outputOptions: { importMetaName }
72
+ }
73
+ } = this;
74
+ return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
75
+ rootOutputDir
76
+ )}, ${importMetaName}.url);`;
77
+ }
78
+
58
79
  /**
59
80
  * @returns {string} runtime code
60
81
  */
61
82
  generate() {
62
- const { compilation, chunk } = this;
83
+ const { compilation, chunk, chunkGraph } = this;
63
84
  const {
64
85
  runtimeTemplate,
65
- chunkGraph,
66
- outputOptions: { importFunctionName, importMetaName }
86
+ outputOptions: { importFunctionName }
67
87
  } = compilation;
68
88
  const fn = RuntimeGlobals.ensureChunkHandlers;
69
89
  const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
@@ -81,7 +101,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
81
101
  );
82
102
  const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
83
103
  const hasJsMatcher = compileBooleanMatcher(conditionMap);
84
- const initialChunkIds = getInitialChunkIds(chunk, chunkGraph);
104
+ const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
85
105
 
86
106
  const outputName = this.compilation.getPath(
87
107
  getChunkFilenameTemplate(chunk, this.compilation.outputOptions),
@@ -102,11 +122,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
102
122
 
103
123
  return Template.asString([
104
124
  withBaseURI
105
- ? Template.asString([
106
- `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
107
- rootOutputDir
108
- )}, ${importMetaName}.url);`
109
- ])
125
+ ? this._generateBaseUri(chunk, rootOutputDir)
110
126
  : "// no baseURI",
111
127
  "",
112
128
  "// object to store loaded and loading chunks",