webpack 5.96.1 → 5.97.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 (64) hide show
  1. package/lib/CssModule.js +5 -0
  2. package/lib/DependencyTemplate.js +2 -2
  3. package/lib/EvalSourceMapDevToolPlugin.js +5 -0
  4. package/lib/FalseIIFEUmdWarning.js +19 -0
  5. package/lib/HotModuleReplacementPlugin.js +4 -0
  6. package/lib/Module.js +6 -0
  7. package/lib/ModuleSourceTypesConstants.js +12 -0
  8. package/lib/NormalModule.js +1 -0
  9. package/lib/RuntimeTemplate.js +7 -0
  10. package/lib/SourceMapDevToolPlugin.js +8 -0
  11. package/lib/WebpackOptionsApply.js +3 -1
  12. package/lib/asset/AssetModulesPlugin.js +7 -2
  13. package/lib/config/defaults.js +52 -36
  14. package/lib/config/normalization.js +0 -1
  15. package/lib/config/target.js +8 -8
  16. package/lib/css/CssGenerator.js +139 -35
  17. package/lib/css/CssLoadingRuntimeModule.js +108 -198
  18. package/lib/css/CssModulesPlugin.js +78 -124
  19. package/lib/css/CssParser.js +545 -121
  20. package/lib/css/walkCssTokens.js +41 -19
  21. package/lib/dependencies/CachedConstDependency.js +2 -1
  22. package/lib/dependencies/ContextDependencyTemplateAsId.js +3 -2
  23. package/lib/dependencies/{CssExportDependency.js → CssIcssExportDependency.js} +35 -35
  24. package/lib/dependencies/CssIcssImportDependency.js +118 -0
  25. package/lib/dependencies/CssIcssSymbolDependency.js +132 -0
  26. package/lib/dependencies/CssImportDependency.js +0 -8
  27. package/lib/dependencies/CssLocalIdentifierDependency.js +69 -73
  28. package/lib/dependencies/CssUrlDependency.js +1 -0
  29. package/lib/esm/ModuleChunkFormatPlugin.js +8 -4
  30. package/lib/esm/ModuleChunkLoadingRuntimeModule.js +17 -10
  31. package/lib/index.js +9 -3
  32. package/lib/javascript/EnableChunkLoadingPlugin.js +2 -4
  33. package/lib/library/AssignLibraryPlugin.js +1 -1
  34. package/lib/library/EnableLibraryPlugin.js +17 -0
  35. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +81 -78
  36. package/lib/node/ReadFileCompileWasmPlugin.js +76 -57
  37. package/lib/optimize/MergeDuplicateChunksPlugin.js +22 -2
  38. package/lib/sharing/ConsumeSharedPlugin.js +35 -12
  39. package/lib/sharing/utils.js +35 -4
  40. package/lib/stats/DefaultStatsFactoryPlugin.js +0 -5
  41. package/lib/util/Queue.js +52 -24
  42. package/lib/util/generateDebugId.js +33 -0
  43. package/lib/util/internalSerializables.js +6 -2
  44. package/lib/wasm/EnableWasmLoadingPlugin.js +36 -25
  45. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +26 -2
  46. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +103 -0
  47. package/lib/wasm-sync/WebAssemblyParser.js +1 -1
  48. package/lib/web/FetchCompileAsyncWasmPlugin.js +43 -44
  49. package/lib/web/FetchCompileWasmPlugin.js +4 -4
  50. package/package.json +4 -4
  51. package/schemas/WebpackOptions.check.js +1 -1
  52. package/schemas/WebpackOptions.json +34 -12
  53. package/schemas/plugins/BannerPlugin.json +1 -1
  54. package/schemas/plugins/SourceMapDevToolPlugin.check.js +1 -1
  55. package/schemas/plugins/SourceMapDevToolPlugin.json +4 -0
  56. package/schemas/plugins/css/CssAutoParserOptions.check.js +1 -1
  57. package/schemas/plugins/css/CssGlobalParserOptions.check.js +1 -1
  58. package/schemas/plugins/css/CssModuleParserOptions.check.js +1 -1
  59. package/schemas/plugins/css/CssParserOptions.check.js +1 -1
  60. package/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.d.ts +7 -0
  61. package/schemas/plugins/optimize/MergeDuplicateChunksPlugin.check.js +6 -0
  62. package/schemas/plugins/optimize/MergeDuplicateChunksPlugin.json +11 -0
  63. package/types.d.ts +84 -23
  64. package/lib/css/CssExportsGenerator.js +0 -207
@@ -9,6 +9,7 @@ const { cssExportConvention } = require("../util/conventions");
9
9
  const createHash = require("../util/createHash");
10
10
  const { makePathsRelative } = require("../util/identifier");
11
11
  const makeSerializable = require("../util/makeSerializable");
12
+ const memoize = require("../util/memoize");
12
13
  const NullDependency = require("./NullDependency");
13
14
 
14
15
  /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
@@ -23,7 +24,6 @@ const NullDependency = require("./NullDependency");
23
24
  /** @typedef {import("../ModuleGraph")} ModuleGraph */
24
25
  /** @typedef {import("../NormalModuleFactory").ResourceDataWithData} ResourceDataWithData */
25
26
  /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
26
- /** @typedef {import("../css/CssExportsGenerator")} CssExportsGenerator */
27
27
  /** @typedef {import("../css/CssGenerator")} CssGenerator */
28
28
  /** @typedef {import("../css/CssParser").Range} Range */
29
29
  /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
@@ -31,6 +31,8 @@ const NullDependency = require("./NullDependency");
31
31
  /** @typedef {import("../util/Hash")} Hash */
32
32
  /** @typedef {import("../util/createHash").Algorithm} Algorithm */
33
33
 
34
+ const getCssParser = memoize(() => require("../css/CssParser"));
35
+
34
36
  /**
35
37
  * @param {string} local css local
36
38
  * @param {CssModule} module module
@@ -40,34 +42,32 @@ const NullDependency = require("./NullDependency");
40
42
  */
41
43
  const getLocalIdent = (local, module, chunkGraph, runtimeTemplate) => {
42
44
  const localIdentName =
43
- /** @type {CssGenerator | CssExportsGenerator} */
45
+ /** @type {CssGenerator} */
44
46
  (module.generator).localIdentName;
45
47
  const relativeResourcePath = makePathsRelative(
46
48
  /** @type {string} */
47
49
  (module.context),
48
- /** @type {string} */ (
49
- /** @type {ResourceDataWithData} */
50
- (module.resourceResolveData).path
51
- )
50
+ module.matchResource || module.resource,
51
+ runtimeTemplate.compilation.compiler.root
52
52
  );
53
53
  const { hashFunction, hashDigest, hashDigestLength, hashSalt, uniqueName } =
54
54
  runtimeTemplate.outputOptions;
55
55
  const hash = createHash(/** @type {Algorithm} */ (hashFunction));
56
+
56
57
  if (hashSalt) {
57
58
  hash.update(hashSalt);
58
59
  }
60
+
59
61
  hash.update(relativeResourcePath);
62
+
60
63
  if (!/\[local\]/.test(localIdentName)) {
61
64
  hash.update(local);
62
65
  }
63
- const localIdentHash = /** @type {string} */ (hash.digest(hashDigest))
64
- // Remove all leading digits
65
- .replace(/^\d+/, "")
66
- // Replace all slashes with underscores (same as in base64url)
67
- .replace(/\//g, "_")
68
- // Remove everything that is not an alphanumeric or underscore
69
- .replace(/[^A-Za-z0-9_]+/g, "_")
70
- .slice(0, hashDigestLength);
66
+
67
+ const localIdentHash =
68
+ /** @type {string} */
69
+ (hash.digest(hashDigest)).slice(0, hashDigestLength);
70
+
71
71
  return runtimeTemplate.compilation
72
72
  .getPath(localIdentName, {
73
73
  filename: relativeResourcePath,
@@ -77,7 +77,8 @@ const getLocalIdent = (local, module, chunkGraph, runtimeTemplate) => {
77
77
  module
78
78
  })
79
79
  .replace(/\[local\]/g, local)
80
- .replace(/\[uniqueName\]/g, /** @type {string} */ (uniqueName));
80
+ .replace(/\[uniqueName\]/g, /** @type {string} */ (uniqueName))
81
+ .replace(/^((-?[0-9])|--)/, "_$1");
81
82
  };
82
83
 
83
84
  class CssLocalIdentifierDependency extends NullDependency {
@@ -91,6 +92,8 @@ class CssLocalIdentifierDependency extends NullDependency {
91
92
  this.name = name;
92
93
  this.range = range;
93
94
  this.prefix = prefix;
95
+ this._conventionNames = undefined;
96
+ this._hashUpdate = undefined;
94
97
  }
95
98
 
96
99
  get type() {
@@ -117,9 +120,9 @@ class CssLocalIdentifierDependency extends NullDependency {
117
120
  */
118
121
  getExports(moduleGraph) {
119
122
  const module = /** @type {CssModule} */ (moduleGraph.getParentModule(this));
120
- const convention = /** @type {CssGenerator | CssExportsGenerator} */ (
121
- module.generator
122
- ).convention;
123
+ const convention =
124
+ /** @type {CssGenerator} */
125
+ (module.generator).convention;
123
126
  const names = this.getExportsConventionNames(this.name, convention);
124
127
  return {
125
128
  exports: names.map(name => ({
@@ -137,20 +140,20 @@ class CssLocalIdentifierDependency extends NullDependency {
137
140
  * @returns {void}
138
141
  */
139
142
  updateHash(hash, { chunkGraph }) {
140
- const module = /** @type {CssModule} */ (
141
- chunkGraph.moduleGraph.getParentModule(this)
142
- );
143
- const generator = /** @type {CssGenerator | CssExportsGenerator} */ (
144
- module.generator
145
- );
146
- const names = this.getExportsConventionNames(
147
- this.name,
148
- generator.convention
149
- );
150
- hash.update("exportsConvention");
151
- hash.update(JSON.stringify(names));
152
- hash.update("localIdentName");
153
- hash.update(generator.localIdentName);
143
+ if (this._hashUpdate === undefined) {
144
+ const module =
145
+ /** @type {CssModule} */
146
+ (chunkGraph.moduleGraph.getParentModule(this));
147
+ const generator =
148
+ /** @type {CssGenerator} */
149
+ (module.generator);
150
+ const names = this.getExportsConventionNames(
151
+ this.name,
152
+ generator.convention
153
+ );
154
+ this._hashUpdate = `exportsConvention|${JSON.stringify(names)}|localIdentName|${JSON.stringify(generator.localIdentName)}`;
155
+ }
156
+ hash.update(this._hashUpdate);
154
157
  }
155
158
 
156
159
  /**
@@ -176,47 +179,43 @@ class CssLocalIdentifierDependency extends NullDependency {
176
179
  }
177
180
  }
178
181
 
179
- /**
180
- * @param {string} str string
181
- * @param {string | boolean} omitUnderscore true if you need to omit underscore
182
- * @returns {string} escaped css identifier
183
- */
184
- const escapeCssIdentifier = (str, omitUnderscore) => {
185
- const escaped = `${str}`.replace(
186
- // cspell:word uffff
187
- /[^a-zA-Z0-9_\u0081-\uFFFF-]/g,
188
- s => `\\${s}`
189
- );
190
- return !omitUnderscore && /^(?!--)[0-9-]/.test(escaped)
191
- ? `_${escaped}`
192
- : escaped;
193
- };
194
-
195
182
  CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTemplate extends (
196
183
  NullDependency.Template
197
184
  ) {
198
185
  /**
199
186
  * @param {Dependency} dependency the dependency for which the template should be applied
200
- * @param {ReplaceSource} source the current replace source which can be modified
187
+ * @param {string} local local name
201
188
  * @param {DependencyTemplateContext} templateContext the context object
202
- * @returns {void}
189
+ * @returns {string} identifier
203
190
  */
204
- apply(
191
+ static getIdentifier(
205
192
  dependency,
206
- source,
207
- {
208
- module: m,
209
- moduleGraph,
210
- chunkGraph,
211
- runtime,
212
- runtimeTemplate,
213
- cssExportsData
214
- }
193
+ local,
194
+ { module: m, chunkGraph, runtimeTemplate }
215
195
  ) {
216
196
  const dep = /** @type {CssLocalIdentifierDependency} */ (dependency);
217
197
  const module = /** @type {CssModule} */ (m);
198
+
199
+ return (
200
+ dep.prefix +
201
+ getCssParser().escapeIdentifier(
202
+ getLocalIdent(local, module, chunkGraph, runtimeTemplate)
203
+ )
204
+ );
205
+ }
206
+
207
+ /**
208
+ * @param {Dependency} dependency the dependency for which the template should be applied
209
+ * @param {ReplaceSource} source the current replace source which can be modified
210
+ * @param {DependencyTemplateContext} templateContext the context object
211
+ * @returns {void}
212
+ */
213
+ apply(dependency, source, templateContext) {
214
+ const { module: m, moduleGraph, runtime, cssData } = templateContext;
215
+ const dep = /** @type {CssLocalIdentifierDependency} */ (dependency);
216
+ const module = /** @type {CssModule} */ (m);
218
217
  const convention =
219
- /** @type {CssGenerator | CssExportsGenerator} */
218
+ /** @type {CssGenerator} */
220
219
  (module.generator).convention;
221
220
  const names = dep.getExportsConventionNames(dep.name, convention);
222
221
  const usedNames =
@@ -228,20 +227,17 @@ CssLocalIdentifierDependency.Template = class CssLocalIdentifierDependencyTempla
228
227
  )
229
228
  .filter(Boolean)
230
229
  );
231
- const used = usedNames.length === 0 ? names[0] : usedNames[0];
232
-
233
- // use the first usedName to generate localIdent, it's shorter when mangle exports enabled
234
- const localIdent =
235
- dep.prefix + getLocalIdent(used, module, chunkGraph, runtimeTemplate);
236
-
237
- source.replace(
238
- dep.range[0],
239
- dep.range[1] - 1,
240
- escapeCssIdentifier(localIdent, dep.prefix)
230
+ const local = usedNames.length === 0 ? names[0] : usedNames[0];
231
+ const identifier = CssLocalIdentifierDependencyTemplate.getIdentifier(
232
+ dep,
233
+ local,
234
+ templateContext
241
235
  );
242
236
 
243
- for (const used of usedNames) {
244
- cssExportsData.exports.set(used, localIdent);
237
+ source.replace(dep.range[0], dep.range[1] - 1, identifier);
238
+
239
+ for (const used of usedNames.concat(names)) {
240
+ cssData.exports.set(used, identifier);
245
241
  }
246
242
  }
247
243
  };
@@ -181,6 +181,7 @@ CssUrlDependency.Template = class CssUrlDependencyTemplate extends (
181
181
  const data =
182
182
  /** @type {NonNullable<CodeGenerationResult["data"]>} */
183
183
  (codeGen.data);
184
+ if (!data) return "data:,";
184
185
  const url = data.get("url");
185
186
  if (!url || !url["css-url"]) return "data:,";
186
187
  return url["css-url"];
@@ -56,15 +56,19 @@ class ModuleChunkFormatPlugin {
56
56
  "HMR is not implemented for module chunk format yet"
57
57
  );
58
58
  } else {
59
- source.add(`export const id = ${JSON.stringify(chunk.id)};\n`);
60
- source.add(`export const ids = ${JSON.stringify(chunk.ids)};\n`);
61
- source.add("export const modules = ");
59
+ source.add(
60
+ `export const __webpack_id__ = ${JSON.stringify(chunk.id)};\n`
61
+ );
62
+ source.add(
63
+ `export const __webpack_ids__ = ${JSON.stringify(chunk.ids)};\n`
64
+ );
65
+ source.add("export const __webpack_modules__ = ");
62
66
  source.add(modules);
63
67
  source.add(";\n");
64
68
  const runtimeModules =
65
69
  chunkGraph.getChunkRuntimeModulesInOrder(chunk);
66
70
  if (runtimeModules.length > 0) {
67
- source.add("export const runtime =\n");
71
+ source.add("export const __webpack_runtime__ =\n");
68
72
  source.add(
69
73
  Template.renderChunkRuntimeModules(
70
74
  runtimeModules,
@@ -111,12 +111,13 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
111
111
  );
112
112
  const { linkPreload, linkPrefetch } =
113
113
  ModuleChunkLoadingRuntimeModule.getCompilationHooks(compilation);
114
+ const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
114
115
  const withPrefetch =
115
- environment.document &&
116
+ (environment.document || isNeutralPlatform) &&
116
117
  this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
117
118
  chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs);
118
119
  const withPreload =
119
- environment.document &&
120
+ (environment.document || isNeutralPlatform) &&
120
121
  this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
121
122
  chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs);
122
123
  const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
@@ -161,29 +162,29 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
161
162
  withLoading || withExternalInstallChunk
162
163
  ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
163
164
  runtimeTemplate.destructureObject(
164
- ["ids", "modules", "runtime"],
165
+ ["__webpack_ids__", "__webpack_modules__", "__webpack_runtime__"],
165
166
  "data"
166
167
  ),
167
168
  '// add "modules" to the modules object,',
168
169
  '// then flag all "ids" as loaded and fire callback',
169
170
  "var moduleId, chunkId, i = 0;",
170
- "for(moduleId in modules) {",
171
+ "for(moduleId in __webpack_modules__) {",
171
172
  Template.indent([
172
- `if(${RuntimeGlobals.hasOwnProperty}(modules, moduleId)) {`,
173
+ `if(${RuntimeGlobals.hasOwnProperty}(__webpack_modules__, moduleId)) {`,
173
174
  Template.indent(
174
- `${RuntimeGlobals.moduleFactories}[moduleId] = modules[moduleId];`
175
+ `${RuntimeGlobals.moduleFactories}[moduleId] = __webpack_modules__[moduleId];`
175
176
  ),
176
177
  "}"
177
178
  ]),
178
179
  "}",
179
- `if(runtime) runtime(${RuntimeGlobals.require});`,
180
- "for(;i < ids.length; i++) {",
180
+ `if(__webpack_runtime__) __webpack_runtime__(${RuntimeGlobals.require});`,
181
+ "for(;i < __webpack_ids__.length; i++) {",
181
182
  Template.indent([
182
- "chunkId = ids[i];",
183
+ "chunkId = __webpack_ids__[i];",
183
184
  `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
184
185
  Template.indent("installedChunks[chunkId][0]();"),
185
186
  "}",
186
- "installedChunks[ids[i]] = 0;"
187
+ "installedChunks[__webpack_ids__[i]] = 0;"
187
188
  ]),
188
189
  "}",
189
190
  withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
@@ -254,6 +255,9 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
254
255
  }) {`,
255
256
  Template.indent([
256
257
  "installedChunks[chunkId] = null;",
258
+ isNeutralPlatform
259
+ ? "if (typeof document === 'undefined') return;"
260
+ : "",
257
261
  linkPrefetch.call(
258
262
  Template.asString([
259
263
  "var link = document.createElement('link');",
@@ -290,6 +294,9 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
290
294
  }) {`,
291
295
  Template.indent([
292
296
  "installedChunks[chunkId] = null;",
297
+ isNeutralPlatform
298
+ ? "if (typeof document === 'undefined') return;"
299
+ : "",
293
300
  linkPreload.call(
294
301
  Template.asString([
295
302
  "var link = document.createElement('link');",
package/lib/index.js CHANGED
@@ -443,6 +443,9 @@ module.exports = mergeExports(fn, {
443
443
  get LimitChunkCountPlugin() {
444
444
  return require("./optimize/LimitChunkCountPlugin");
445
445
  },
446
+ get MergeDuplicateChunksPlugin() {
447
+ return require("./optimize/MergeDuplicateChunksPlugin.js");
448
+ },
446
449
  get MinChunkSizePlugin() {
447
450
  return require("./optimize/MinChunkSizePlugin");
448
451
  },
@@ -479,12 +482,12 @@ module.exports = mergeExports(fn, {
479
482
  },
480
483
 
481
484
  web: {
482
- get FetchCompileAsyncWasmPlugin() {
483
- return require("./web/FetchCompileAsyncWasmPlugin");
484
- },
485
485
  get FetchCompileWasmPlugin() {
486
486
  return require("./web/FetchCompileWasmPlugin");
487
487
  },
488
+ get FetchCompileAsyncWasmPlugin() {
489
+ return require("./web/FetchCompileAsyncWasmPlugin");
490
+ },
488
491
  get JsonpChunkLoadingRuntimeModule() {
489
492
  return require("./web/JsonpChunkLoadingRuntimeModule");
490
493
  },
@@ -523,6 +526,9 @@ module.exports = mergeExports(fn, {
523
526
  },
524
527
  get ReadFileCompileWasmPlugin() {
525
528
  return require("./node/ReadFileCompileWasmPlugin");
529
+ },
530
+ get ReadFileCompileAsyncWasmPlugin() {
531
+ return require("./node/ReadFileCompileAsyncWasmPlugin");
526
532
  }
527
533
  },
528
534
 
@@ -101,14 +101,12 @@ class EnableChunkLoadingPlugin {
101
101
  }).apply(compiler);
102
102
  break;
103
103
  }
104
- case "import": {
104
+ case "import":
105
+ case "universal": {
105
106
  const ModuleChunkLoadingPlugin = require("../esm/ModuleChunkLoadingPlugin");
106
107
  new ModuleChunkLoadingPlugin().apply(compiler);
107
108
  break;
108
109
  }
109
- case "universal":
110
- // TODO implement universal chunk loading
111
- throw new Error("Universal Chunk Loading is not implemented yet");
112
110
  default:
113
111
  throw new Error(`Unsupported chunk loading type ${type}.
114
112
  Plugins which provide custom chunk loading types must call EnableChunkLoadingPlugin.setEnabled(compiler, type) to disable this error.`);
@@ -330,7 +330,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
330
330
  exports = "__webpack_exports_export__";
331
331
  }
332
332
  result.add(
333
- `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n`
333
+ `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n`
334
334
  );
335
335
  result.add(
336
336
  `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
@@ -208,6 +208,23 @@ class EnableLibraryPlugin {
208
208
  }
209
209
  case "umd":
210
210
  case "umd2": {
211
+ if (compiler.options.output.iife === false) {
212
+ compiler.options.output.iife = true;
213
+
214
+ class WarnFalseIifeUmdPlugin {
215
+ apply(compiler) {
216
+ compiler.hooks.thisCompilation.tap(
217
+ "WarnFalseIifeUmdPlugin",
218
+ compilation => {
219
+ const FalseIIFEUmdWarning = require("../FalseIIFEUmdWarning");
220
+ compilation.warnings.push(new FalseIIFEUmdWarning());
221
+ }
222
+ );
223
+ }
224
+ }
225
+
226
+ new WarnFalseIifeUmdPlugin().apply(compiler);
227
+ }
211
228
  enableExportProperty();
212
229
  const UmdLibraryPlugin = require("./UmdLibraryPlugin");
213
230
  new UmdLibraryPlugin({
@@ -13,9 +13,18 @@ const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRun
13
13
  /** @typedef {import("../Chunk")} Chunk */
14
14
  /** @typedef {import("../Compiler")} Compiler */
15
15
 
16
+ /**
17
+ * @typedef {object} ReadFileCompileAsyncWasmPluginOptions
18
+ * @property {boolean} [import] use import?
19
+ */
20
+
21
+ const PLUGIN_NAME = "ReadFileCompileAsyncWasmPlugin";
22
+
16
23
  class ReadFileCompileAsyncWasmPlugin {
17
- constructor({ type = "async-node", import: useImport = false } = {}) {
18
- this._type = type;
24
+ /**
25
+ * @param {ReadFileCompileAsyncWasmPluginOptions} [options] options object
26
+ */
27
+ constructor({ import: useImport = false } = {}) {
19
28
  this._import = useImport;
20
29
  }
21
30
 
@@ -25,32 +34,53 @@ class ReadFileCompileAsyncWasmPlugin {
25
34
  * @returns {void}
26
35
  */
27
36
  apply(compiler) {
28
- compiler.hooks.thisCompilation.tap(
29
- "ReadFileCompileAsyncWasmPlugin",
30
- compilation => {
31
- const globalWasmLoading = compilation.outputOptions.wasmLoading;
32
- /**
33
- * @param {Chunk} chunk chunk
34
- * @returns {boolean} true, if wasm loading is enabled for the chunk
35
- */
36
- const isEnabledForChunk = chunk => {
37
- const options = chunk.getEntryOptions();
38
- const wasmLoading =
39
- options && options.wasmLoading !== undefined
40
- ? options.wasmLoading
41
- : globalWasmLoading;
42
- return wasmLoading === this._type;
43
- };
44
- const { importMetaName } = compilation.outputOptions;
45
- /**
46
- * @type {(path: string) => string}
47
- */
48
- const generateLoadBinaryCode = this._import
49
- ? path =>
50
- Template.asString([
51
- "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
37
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
38
+ const globalWasmLoading = compilation.outputOptions.wasmLoading;
39
+ /**
40
+ * @param {Chunk} chunk chunk
41
+ * @returns {boolean} true, if wasm loading is enabled for the chunk
42
+ */
43
+ const isEnabledForChunk = chunk => {
44
+ const options = chunk.getEntryOptions();
45
+ const wasmLoading =
46
+ options && options.wasmLoading !== undefined
47
+ ? options.wasmLoading
48
+ : globalWasmLoading;
49
+ return wasmLoading === "async-node";
50
+ };
51
+
52
+ /**
53
+ * @param {string} path path to wasm file
54
+ * @returns {string} generated code to load the wasm file
55
+ */
56
+ const generateLoadBinaryCode = this._import
57
+ ? path =>
58
+ Template.asString([
59
+ "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
60
+ Template.indent([
61
+ `readFile(new URL(${path}, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`,
62
+ Template.indent([
63
+ "if (err) return reject(err);",
64
+ "",
65
+ "// Fake fetch response",
66
+ "resolve({",
67
+ Template.indent(["arrayBuffer() { return buffer; }"]),
68
+ "});"
69
+ ]),
70
+ "});"
71
+ ]),
72
+ "}))"
73
+ ])
74
+ : path =>
75
+ Template.asString([
76
+ "new Promise(function (resolve, reject) {",
77
+ Template.indent([
78
+ "try {",
52
79
  Template.indent([
53
- `readFile(new URL(${path}, ${importMetaName}.url), (err, buffer) => {`,
80
+ "var { readFile } = require('fs');",
81
+ "var { join } = require('path');",
82
+ "",
83
+ `readFile(join(__dirname, ${path}), function(err, buffer){`,
54
84
  Template.indent([
55
85
  "if (err) return reject(err);",
56
86
  "",
@@ -61,59 +91,32 @@ class ReadFileCompileAsyncWasmPlugin {
61
91
  ]),
62
92
  "});"
63
93
  ]),
64
- "}))"
65
- ])
66
- : path =>
67
- Template.asString([
68
- "new Promise(function (resolve, reject) {",
69
- Template.indent([
70
- "try {",
71
- Template.indent([
72
- "var { readFile } = require('fs');",
73
- "var { join } = require('path');",
74
- "",
75
- `readFile(join(__dirname, ${path}), function(err, buffer){`,
76
- Template.indent([
77
- "if (err) return reject(err);",
78
- "",
79
- "// Fake fetch response",
80
- "resolve({",
81
- Template.indent(["arrayBuffer() { return buffer; }"]),
82
- "});"
83
- ]),
84
- "});"
85
- ]),
86
- "} catch (err) { reject(err); }"
87
- ]),
88
- "})"
89
- ]);
94
+ "} catch (err) { reject(err); }"
95
+ ]),
96
+ "})"
97
+ ]);
90
98
 
91
- compilation.hooks.runtimeRequirementInTree
92
- .for(RuntimeGlobals.instantiateWasm)
93
- .tap(
94
- "ReadFileCompileAsyncWasmPlugin",
95
- (chunk, set, { chunkGraph }) => {
96
- if (!isEnabledForChunk(chunk)) return;
97
- if (
98
- !chunkGraph.hasModuleInGraph(
99
- chunk,
100
- m => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
101
- )
102
- ) {
103
- return;
104
- }
105
- set.add(RuntimeGlobals.publicPath);
106
- compilation.addRuntimeModule(
107
- chunk,
108
- new AsyncWasmLoadingRuntimeModule({
109
- generateLoadBinaryCode,
110
- supportsStreaming: false
111
- })
112
- );
113
- }
99
+ compilation.hooks.runtimeRequirementInTree
100
+ .for(RuntimeGlobals.instantiateWasm)
101
+ .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
102
+ if (!isEnabledForChunk(chunk)) return;
103
+ if (
104
+ !chunkGraph.hasModuleInGraph(
105
+ chunk,
106
+ m => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
107
+ )
108
+ ) {
109
+ return;
110
+ }
111
+ compilation.addRuntimeModule(
112
+ chunk,
113
+ new AsyncWasmLoadingRuntimeModule({
114
+ generateLoadBinaryCode,
115
+ supportsStreaming: false
116
+ })
114
117
  );
115
- }
116
- );
118
+ });
119
+ });
117
120
  }
118
121
  }
119
122