webpack 4.1.0 → 4.4.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 (118) hide show
  1. package/README.md +719 -721
  2. package/bin/webpack.js +69 -10
  3. package/lib/APIPlugin.js +84 -84
  4. package/lib/AmdMainTemplatePlugin.js +75 -77
  5. package/lib/AsyncDependencyToInitialChunkError.js +21 -23
  6. package/lib/BannerPlugin.js +101 -101
  7. package/lib/Chunk.js +477 -469
  8. package/lib/ChunkTemplate.js +51 -53
  9. package/lib/Compilation.js +1858 -1851
  10. package/lib/Compiler.js +493 -478
  11. package/lib/ConcurrentCompilationError.js +19 -0
  12. package/lib/ContextModule.js +696 -685
  13. package/lib/ContextModuleFactory.js +245 -243
  14. package/lib/DefinePlugin.js +197 -197
  15. package/lib/DelegatedModule.js +101 -101
  16. package/lib/DependenciesBlockVariable.js +51 -52
  17. package/lib/Dependency.js +53 -52
  18. package/lib/DllModule.js +54 -54
  19. package/lib/DllModuleFactory.js +29 -29
  20. package/lib/EnvironmentPlugin.js +65 -67
  21. package/lib/EvalDevToolModuleTemplatePlugin.js +60 -60
  22. package/lib/EvalSourceMapDevToolModuleTemplatePlugin.js +105 -105
  23. package/lib/ExportPropertyMainTemplatePlugin.js +40 -40
  24. package/lib/ExternalModule.js +159 -159
  25. package/lib/FunctionModuleTemplatePlugin.js +98 -98
  26. package/lib/HotModuleReplacement.runtime.js +631 -631
  27. package/lib/HotModuleReplacementPlugin.js +407 -406
  28. package/lib/HotUpdateChunkTemplate.js +78 -80
  29. package/lib/JavascriptGenerator.js +228 -229
  30. package/lib/JavascriptModulesPlugin.js +184 -158
  31. package/lib/JsonGenerator.js +42 -42
  32. package/lib/MainTemplate.js +406 -402
  33. package/lib/Module.js +343 -340
  34. package/lib/ModuleBuildError.js +42 -42
  35. package/lib/ModuleError.js +28 -28
  36. package/lib/ModuleFilenameHelpers.js +166 -166
  37. package/lib/ModuleTemplate.js +77 -79
  38. package/lib/ModuleWarning.js +30 -30
  39. package/lib/MultiCompiler.js +271 -259
  40. package/lib/MultiModule.js +78 -75
  41. package/lib/MultiModuleFactory.js +23 -23
  42. package/lib/MultiWatching.js +38 -37
  43. package/lib/NoModeWarning.js +23 -21
  44. package/lib/NormalModule.js +478 -470
  45. package/lib/NormalModuleFactory.js +483 -481
  46. package/lib/OptionsDefaulter.js +80 -86
  47. package/lib/Parser.js +2074 -2071
  48. package/lib/ProgressPlugin.js +231 -231
  49. package/lib/RawModule.js +54 -55
  50. package/lib/RecordIdsPlugin.js +160 -160
  51. package/lib/RemovedPluginError.js +13 -13
  52. package/lib/ResolverFactory.js +64 -67
  53. package/lib/RuntimeTemplate.js +267 -297
  54. package/lib/SetVarMainTemplatePlugin.js +57 -57
  55. package/lib/SourceMapDevToolPlugin.js +302 -308
  56. package/lib/Stats.js +1234 -1212
  57. package/lib/Template.js +205 -205
  58. package/lib/TemplatedPathPlugin.js +170 -143
  59. package/lib/UmdMainTemplatePlugin.js +264 -269
  60. package/lib/Watching.js +193 -193
  61. package/lib/WebAssemblyParser.js +50 -54
  62. package/lib/WebpackOptionsApply.js +401 -401
  63. package/lib/WebpackOptionsDefaulter.js +337 -317
  64. package/lib/WebpackOptionsValidationError.js +316 -319
  65. package/lib/debug/ProfilingPlugin.js +409 -405
  66. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +328 -311
  67. package/lib/dependencies/AMDRequireContextDependency.js +20 -20
  68. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +270 -241
  69. package/lib/dependencies/HarmonyAcceptImportDependency.js +23 -23
  70. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +620 -606
  71. package/lib/dependencies/HarmonyExportSpecifierDependency.js +53 -53
  72. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +214 -214
  73. package/lib/dependencies/HarmonyImportSpecifierDependency.js +154 -156
  74. package/lib/dependencies/ImportDependenciesBlock.js +17 -17
  75. package/lib/dependencies/ImportDependency.js +34 -34
  76. package/lib/dependencies/ImportEagerDependency.js +32 -32
  77. package/lib/dependencies/ImportParserPlugin.js +175 -179
  78. package/lib/dependencies/ImportWeakDependency.js +34 -34
  79. package/lib/dependencies/JsonExportsDependency.js +25 -25
  80. package/lib/dependencies/ModuleDependency.js +20 -20
  81. package/lib/dependencies/NullDependency.js +20 -20
  82. package/lib/dependencies/RequireContextDependency.js +22 -22
  83. package/lib/dependencies/RequireIncludeDependency.js +40 -40
  84. package/lib/dependencies/WebpackMissingModule.js +20 -22
  85. package/lib/node/NodeChunkTemplatePlugin.js +31 -31
  86. package/lib/node/NodeHotUpdateChunkTemplatePlugin.js +36 -36
  87. package/lib/node/NodeMainTemplatePlugin.js +320 -273
  88. package/lib/node/ReadFileCompileWasmMainTemplatePlugin.js +113 -115
  89. package/lib/optimize/AggressiveSplittingPlugin.js +281 -281
  90. package/lib/optimize/ConcatenatedModule.js +1364 -1366
  91. package/lib/optimize/RemoveParentModulesPlugin.js +114 -114
  92. package/lib/optimize/SplitChunksPlugin.js +519 -491
  93. package/lib/performance/SizeLimitsPlugin.js +105 -105
  94. package/lib/util/TrackingSet.js +35 -35
  95. package/lib/util/objectToMap.js +10 -10
  96. package/lib/wasm/WasmModuleTemplatePlugin.js +106 -106
  97. package/lib/web/JsonpChunkTemplatePlugin.js +47 -47
  98. package/lib/web/JsonpExportMainTemplatePlugin.js +47 -47
  99. package/lib/web/JsonpHotUpdateChunkTemplatePlugin.js +39 -39
  100. package/lib/web/JsonpMainTemplatePlugin.js +425 -403
  101. package/lib/webpack.js +182 -179
  102. package/lib/webworker/WebWorkerChunkTemplatePlugin.js +35 -35
  103. package/lib/webworker/WebWorkerHotUpdateChunkTemplatePlugin.js +40 -40
  104. package/lib/webworker/WebWorkerMainTemplatePlugin.js +177 -154
  105. package/package.json +9 -8
  106. package/schemas/WebpackOptions.json +1973 -1951
  107. package/schemas/ajv.absolutePath.js +55 -29
  108. package/schemas/plugins/BannerPlugin.json +85 -85
  109. package/schemas/plugins/DllPlugin.json +28 -28
  110. package/schemas/plugins/DllReferencePlugin.json +99 -99
  111. package/schemas/plugins/HashedModuleIdsPlugin.json +24 -24
  112. package/schemas/plugins/LoaderOptionsPlugin.json +26 -26
  113. package/schemas/plugins/SourceMapDevToolPlugin.json +187 -187
  114. package/schemas/plugins/WatchIgnorePlugin.json +16 -16
  115. package/schemas/plugins/debug/ProfilingPlugin.json +12 -12
  116. package/schemas/plugins/optimize/AggressiveSplittingPlugin.json +22 -22
  117. package/schemas/plugins/optimize/LimitChunkCountPlugin.json +15 -15
  118. package/schemas/plugins/optimize/MinChunkSizePlugin.json +13 -13
@@ -1,685 +1,696 @@
1
- /*
2
- MIT License http://www.opensource.org/licenses/mit-license.php
3
- Author Tobias Koppers @sokra
4
- */
5
- "use strict";
6
- const path = require("path");
7
- const util = require("util");
8
- const Module = require("./Module");
9
- const OriginalSource = require("webpack-sources").OriginalSource;
10
- const RawSource = require("webpack-sources").RawSource;
11
- const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
12
- const Template = require("./Template");
13
-
14
- class ContextModule extends Module {
15
- // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"
16
- // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp }
17
- // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void
18
- // options: ContextOptions
19
- constructor(resolveDependencies, options) {
20
- let resource;
21
- let resourceQuery;
22
- const queryIdx = options.resource.indexOf("?");
23
- if (queryIdx >= 0) {
24
- resource = options.resource.substr(0, queryIdx);
25
- resourceQuery = options.resource.substr(queryIdx);
26
- } else {
27
- resource = options.resource;
28
- resourceQuery = "";
29
- }
30
-
31
- super("javascript/dynamic", resource);
32
-
33
- // Info from Factory
34
- this.resolveDependencies = resolveDependencies;
35
- this.options = Object.assign({}, options, {
36
- resource: resource,
37
- resourceQuery: resourceQuery
38
- });
39
- if (options.resolveOptions !== undefined)
40
- this.resolveOptions = options.resolveOptions;
41
-
42
- // Info from Build
43
- this._contextDependencies = new Set([this.context]);
44
-
45
- if (typeof options.mode !== "string")
46
- throw new Error("options.mode is a required option");
47
- }
48
-
49
- prettyRegExp(regexString) {
50
- // remove the "/" at the front and the beginning
51
- // "/foo/" -> "foo"
52
- return regexString.substring(1, regexString.length - 1);
53
- }
54
-
55
- contextify(context, request) {
56
- return request
57
- .split("!")
58
- .map(subrequest => {
59
- let rp = path.relative(context, subrequest);
60
- if (path.sep === "\\") rp = rp.replace(/\\/g, "/");
61
- if (rp.indexOf("../") !== 0) rp = "./" + rp;
62
- return rp;
63
- })
64
- .join("!");
65
- }
66
-
67
- identifier() {
68
- let identifier = this.context;
69
- if (this.options.resourceQuery)
70
- identifier += ` ${this.options.resourceQuery}`;
71
- if (this.options.mode) identifier += ` ${this.options.mode}`;
72
- if (!this.options.recursive) identifier += " nonrecursive";
73
- if (this.options.addon) identifier += ` ${this.options.addon}`;
74
- if (this.options.regExp) identifier += ` ${this.options.regExp}`;
75
- if (this.options.include) identifier += ` include: ${this.options.include}`;
76
- if (this.options.exclude) identifier += ` exclude: ${this.options.exclude}`;
77
- if (this.options.namespaceObject === "strict")
78
- identifier += " strict namespace object";
79
- else if (this.options.namespaceObject) identifier += " namespace object";
80
-
81
- return identifier;
82
- }
83
-
84
- readableIdentifier(requestShortener) {
85
- let identifier = requestShortener.shorten(this.context);
86
- if (this.options.resourceQuery)
87
- identifier += ` ${this.options.resourceQuery}`;
88
- if (this.options.mode) identifier += ` ${this.options.mode}`;
89
- if (!this.options.recursive) identifier += " nonrecursive";
90
- if (this.options.addon)
91
- identifier += ` ${requestShortener.shorten(this.options.addon)}`;
92
- if (this.options.regExp)
93
- identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`;
94
- if (this.options.include)
95
- identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`;
96
- if (this.options.exclude)
97
- identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`;
98
- if (this.options.namespaceObject === "strict")
99
- identifier += " strict namespace object";
100
- else if (this.options.namespaceObject) identifier += " namespace object";
101
-
102
- return identifier;
103
- }
104
-
105
- libIdent(options) {
106
- let identifier = this.contextify(options.context, this.context);
107
- if (this.options.mode) identifier += ` ${this.options.mode}`;
108
- if (this.options.recursive) identifier += " recursive";
109
- if (this.options.addon)
110
- identifier += ` ${this.contextify(options.context, this.options.addon)}`;
111
- if (this.options.regExp)
112
- identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`;
113
- if (this.options.include)
114
- identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`;
115
- if (this.options.exclude)
116
- identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`;
117
-
118
- return identifier;
119
- }
120
-
121
- needRebuild(fileTimestamps, contextTimestamps) {
122
- const ts = contextTimestamps.get(this.context);
123
- if (!ts) {
124
- return true;
125
- }
126
-
127
- return ts >= this.buildInfo.builtTime;
128
- }
129
-
130
- build(options, compilation, resolver, fs, callback) {
131
- this.built = true;
132
- this.buildMeta = {};
133
- this.buildInfo = {
134
- builtTime: Date.now(),
135
- contextDependencies: this._contextDependencies
136
- };
137
- this.resolveDependencies(fs, this.options, (err, dependencies) => {
138
- if (err) return callback(err);
139
-
140
- // abort if something failed
141
- // this will create an empty context
142
- if (!dependencies) {
143
- callback();
144
- return;
145
- }
146
-
147
- // enhance dependencies with meta info
148
- for (const dep of dependencies) {
149
- dep.loc = dep.userRequest;
150
- dep.request = this.options.addon + dep.request;
151
- }
152
-
153
- if (this.options.mode === "sync" || this.options.mode === "eager") {
154
- // if we have an sync or eager context
155
- // just add all dependencies and continue
156
- this.dependencies = dependencies;
157
- } else if (this.options.mode === "lazy-once") {
158
- // for the lazy-once mode create a new async dependency block
159
- // and add that block to this context
160
- if (dependencies.length > 0) {
161
- const block = new AsyncDependenciesBlock(
162
- this.options.chunkName,
163
- this
164
- );
165
- for (const dep of dependencies) {
166
- block.addDependency(dep);
167
- }
168
- this.addBlock(block);
169
- }
170
- } else if (
171
- this.options.mode === "weak" ||
172
- this.options.mode === "async-weak"
173
- ) {
174
- // we mark all dependencies as weak
175
- for (const dep of dependencies) {
176
- dep.weak = true;
177
- }
178
- this.dependencies = dependencies;
179
- } else if (this.options.mode === "lazy") {
180
- // if we are lazy create a new async dependency block per dependency
181
- // and add all blocks to this context
182
- let index = 0;
183
- for (const dep of dependencies) {
184
- let chunkName = this.options.chunkName;
185
- if (chunkName) {
186
- if (!/\[(index|request)\]/.test(chunkName)) chunkName += "[index]";
187
- chunkName = chunkName.replace(/\[index\]/g, index++);
188
- chunkName = chunkName.replace(
189
- /\[request\]/g,
190
- Template.toPath(dep.userRequest)
191
- );
192
- }
193
- const block = new AsyncDependenciesBlock(
194
- chunkName,
195
- dep.module,
196
- dep.loc,
197
- dep.userRequest
198
- );
199
- block.addDependency(dep);
200
- this.addBlock(block);
201
- }
202
- } else {
203
- callback(
204
- new Error(`Unsupported mode "${this.options.mode}" in context`)
205
- );
206
- return;
207
- }
208
- callback();
209
- });
210
- }
211
-
212
- getUserRequestMap(dependencies) {
213
- // if we filter first we get a new array
214
- // therefor we dont need to create a clone of dependencies explicitly
215
- // therefore the order of this is !important!
216
- return dependencies
217
- .filter(dependency => dependency.module)
218
- .sort((a, b) => {
219
- if (a.userRequest === b.userRequest) {
220
- return 0;
221
- }
222
- return a.userRequest < b.userRequest ? -1 : 1;
223
- })
224
- .reduce((map, dep) => {
225
- map[dep.userRequest] = dep.module.id;
226
- return map;
227
- }, Object.create(null));
228
- }
229
-
230
- getFakeMap(dependencies) {
231
- if (!this.options.namespaceObject) return 1;
232
- // if we filter first we get a new array
233
- // therefor we dont need to create a clone of dependencies explicitly
234
- // therefore the order of this is !important!
235
- let hasNonHarmony = false;
236
- let hasNamespace = false;
237
- let hasNamed = false;
238
- const fakeMap = dependencies
239
- .filter(dependency => dependency.module)
240
- .sort((a, b) => {
241
- return b.module.id - a.module.id;
242
- })
243
- .reduce((map, dep) => {
244
- const exportsType =
245
- dep.module.buildMeta && dep.module.buildMeta.exportsType;
246
- if (!exportsType) hasNonHarmony = true;
247
- if (exportsType === "namespace") hasNamespace = true;
248
- if (exportsType === "named") hasNamed = true;
249
- map[dep.module.id] =
250
- {
251
- namespace: 1,
252
- named: 2
253
- }[exportsType] || 0;
254
- return map;
255
- }, Object.create(null));
256
- if (!hasNamespace && hasNonHarmony && !hasNamed) return 0;
257
- if (hasNamespace && !hasNonHarmony && !hasNamed) return 1;
258
- if (!hasNamespace && !hasNonHarmony && hasNamed) return 2;
259
- if (!hasNamespace && !hasNonHarmony && !hasNamed) return 1;
260
- return fakeMap;
261
- }
262
-
263
- getFakeMapInitStatement(fakeMap) {
264
- return typeof fakeMap === "object"
265
- ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
266
- : "";
267
- }
268
-
269
- getReturn(type) {
270
- if (type === 1) return "module";
271
- if (type === 2)
272
- return 'Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module })';
273
- if (type === 0) {
274
- if (this.options.namespaceObject === "strict") {
275
- return '/* fake namespace object */ { "default": module }';
276
- } else {
277
- return '(typeof module === "object" && module && module.__esModule ? module : Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module }))';
278
- }
279
- }
280
- }
281
-
282
- getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") {
283
- if (typeof fakeMap === "number")
284
- return `return ${this.getReturn(fakeMap)};`;
285
- return `return ${fakeMapDataExpression} === 1 ? ${this.getReturn(1)} : ${
286
- fakeMapDataExpression
287
- } ? ${this.getReturn(2)} : ${this.getReturn(0)};`;
288
- }
289
-
290
- getSyncSource(dependencies, id) {
291
- const map = this.getUserRequestMap(dependencies);
292
- const fakeMap = this.getFakeMap(dependencies);
293
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
294
-
295
- return `var map = ${JSON.stringify(map, null, "\t")};
296
- ${this.getFakeMapInitStatement(fakeMap)}
297
-
298
- function webpackContext(req) {
299
- var id = webpackContextResolve(req);
300
- var module = __webpack_require__(id);
301
- ${returnModuleObject}
302
- }
303
- function webpackContextResolve(req) {
304
- var id = map[req];
305
- if(!(id + 1)) { // check for number or string
306
- var e = new Error('Cannot find module "' + req + '".');
307
- e.code = 'MODULE_NOT_FOUND';
308
- throw e;
309
- }
310
- return id;
311
- }
312
- webpackContext.keys = function webpackContextKeys() {
313
- return Object.keys(map);
314
- };
315
- webpackContext.resolve = webpackContextResolve;
316
- module.exports = webpackContext;
317
- webpackContext.id = ${JSON.stringify(id)};`;
318
- }
319
-
320
- getWeakSyncSource(dependencies, id) {
321
- const map = this.getUserRequestMap(dependencies);
322
- const fakeMap = this.getFakeMap(dependencies);
323
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
324
-
325
- return `var map = ${JSON.stringify(map, null, "\t")};
326
- ${this.getFakeMapInitStatement(fakeMap)}
327
-
328
- function webpackContext(req) {
329
- var id = webpackContextResolve(req);
330
- if(!__webpack_require__.m[id]) {
331
- var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
332
- e.code = 'MODULE_NOT_FOUND';
333
- throw e;
334
- }
335
- var module = __webpack_require__(id);
336
- ${returnModuleObject}
337
- }
338
- function webpackContextResolve(req) {
339
- var id = map[req];
340
- if(!(id + 1)) { // check for number or string
341
- var e = new Error('Cannot find module "' + req + '".');
342
- e.code = 'MODULE_NOT_FOUND';
343
- throw e;
344
- }
345
- return id;
346
- }
347
- webpackContext.keys = function webpackContextKeys() {
348
- return Object.keys(map);
349
- };
350
- webpackContext.resolve = webpackContextResolve;
351
- webpackContext.id = ${JSON.stringify(id)};
352
- module.exports = webpackContext;`;
353
- }
354
-
355
- getAsyncWeakSource(dependencies, id) {
356
- const map = this.getUserRequestMap(dependencies);
357
- const fakeMap = this.getFakeMap(dependencies);
358
- const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
359
-
360
- return `var map = ${JSON.stringify(map, null, "\t")};
361
- ${this.getFakeMapInitStatement(fakeMap)}
362
-
363
- function webpackAsyncContext(req) {
364
- return webpackAsyncContextResolve(req).then(function(id) {
365
- if(!__webpack_require__.m[id]) {
366
- var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
367
- e.code = 'MODULE_NOT_FOUND';
368
- throw e;
369
- }
370
- var module = __webpack_require__(id);
371
- ${returnModuleObject}
372
- });
373
- }
374
- function webpackAsyncContextResolve(req) {
375
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
376
- // uncaught exception popping up in devtools
377
- return Promise.resolve().then(function() {
378
- var id = map[req];
379
- if(!(id + 1)) { // check for number or string
380
- var e = new Error('Cannot find module "' + req + '".');
381
- e.code = 'MODULE_NOT_FOUND';
382
- throw e;
383
- }
384
- return id;
385
- });
386
- }
387
- webpackAsyncContext.keys = function webpackAsyncContextKeys() {
388
- return Object.keys(map);
389
- };
390
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
391
- webpackAsyncContext.id = ${JSON.stringify(id)};
392
- module.exports = webpackAsyncContext;`;
393
- }
394
-
395
- getEagerSource(dependencies, id) {
396
- const map = this.getUserRequestMap(dependencies);
397
- const fakeMap = this.getFakeMap(dependencies);
398
- const thenFunction =
399
- fakeMap !== 1
400
- ? `function(id) {
401
- var module = __webpack_require__(id);
402
- ${this.getReturnModuleObjectSource(fakeMap)}
403
- }`
404
- : "__webpack_require__";
405
- return `var map = ${JSON.stringify(map, null, "\t")};
406
- ${this.getFakeMapInitStatement(fakeMap)}
407
-
408
- function webpackAsyncContext(req) {
409
- return webpackAsyncContextResolve(req).then(${thenFunction});
410
- }
411
- function webpackAsyncContextResolve(req) {
412
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
413
- // uncaught exception popping up in devtools
414
- return Promise.resolve().then(function() {
415
- var id = map[req];
416
- if(!(id + 1)) { // check for number or string
417
- var e = new Error('Cannot find module "' + req + '".');
418
- e.code = 'MODULE_NOT_FOUND';
419
- throw e;
420
- }
421
- return id;
422
- });
423
- }
424
- webpackAsyncContext.keys = function webpackAsyncContextKeys() {
425
- return Object.keys(map);
426
- };
427
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
428
- webpackAsyncContext.id = ${JSON.stringify(id)};
429
- module.exports = webpackAsyncContext;`;
430
- }
431
-
432
- getLazyOnceSource(block, dependencies, id, runtimeTemplate) {
433
- const promise = runtimeTemplate.blockPromise({
434
- block,
435
- message: "lazy-once context"
436
- });
437
- const map = this.getUserRequestMap(dependencies);
438
- const fakeMap = this.getFakeMap(dependencies);
439
- const thenFunction =
440
- fakeMap !== 1
441
- ? `function(id) {
442
- var module = __webpack_require__(id);
443
- ${this.getReturnModuleObjectSource(fakeMap)};
444
- }`
445
- : "__webpack_require__";
446
-
447
- return `var map = ${JSON.stringify(map, null, "\t")};
448
- ${this.getFakeMapInitStatement(fakeMap)}
449
-
450
- function webpackAsyncContext(req) {
451
- return webpackAsyncContextResolve(req).then(${thenFunction});
452
- }
453
- function webpackAsyncContextResolve(req) {
454
- return ${promise}.then(function() {
455
- var id = map[req];
456
- if(!(id + 1)) { // check for number or string
457
- var e = new Error('Cannot find module "' + req + '".');
458
- e.code = 'MODULE_NOT_FOUND';
459
- throw e;
460
- }
461
- return id;
462
- });
463
- }
464
- webpackAsyncContext.keys = function webpackAsyncContextKeys() {
465
- return Object.keys(map);
466
- };
467
- webpackAsyncContext.resolve = webpackAsyncContextResolve;
468
- webpackAsyncContext.id = ${JSON.stringify(id)};
469
- module.exports = webpackAsyncContext;`;
470
- }
471
-
472
- getLazySource(blocks, id) {
473
- let hasMultipleOrNoChunks = false;
474
- const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0]));
475
- const map = blocks
476
- .filter(block => block.dependencies[0].module)
477
- .map(block => ({
478
- dependency: block.dependencies[0],
479
- block: block,
480
- userRequest: block.dependencies[0].userRequest
481
- }))
482
- .sort((a, b) => {
483
- if (a.userRequest === b.userRequest) return 0;
484
- return a.userRequest < b.userRequest ? -1 : 1;
485
- })
486
- .reduce((map, item) => {
487
- const chunks =
488
- (item.block.chunkGroup && item.block.chunkGroup.chunks) || [];
489
- if (chunks.length !== 1) {
490
- hasMultipleOrNoChunks = true;
491
- }
492
- const arrayStart = [item.dependency.module.id];
493
- if (typeof fakeMap === "object")
494
- arrayStart.push(fakeMap[item.dependency.module.id]);
495
- map[item.userRequest] = arrayStart.concat(
496
- chunks.map(chunk => chunk.id)
497
- );
498
-
499
- return map;
500
- }, Object.create(null));
501
-
502
- const chunksStartPosition = typeof fakeMap === "object" ? 2 : 1;
503
- const requestPrefix = hasMultipleOrNoChunks
504
- ? `Promise.all(ids.slice(${
505
- chunksStartPosition
506
- }).map(__webpack_require__.e))`
507
- : `__webpack_require__.e(ids[${chunksStartPosition}])`;
508
- const returnModuleObject = this.getReturnModuleObjectSource(
509
- fakeMap,
510
- "ids[1]"
511
- );
512
-
513
- return `var map = ${JSON.stringify(map, null, "\t")};
514
- function webpackAsyncContext(req) {
515
- var ids = map[req];
516
- if(!ids) {
517
- return Promise.resolve().then(function() {
518
- var e = new Error('Cannot find module "' + req + '".');
519
- e.code = 'MODULE_NOT_FOUND';
520
- throw e;
521
- });
522
- }
523
- return ${requestPrefix}.then(function() {
524
- var module = __webpack_require__(ids[0]);
525
- ${returnModuleObject}
526
- });
527
- }
528
- webpackAsyncContext.keys = function webpackAsyncContextKeys() {
529
- return Object.keys(map);
530
- };
531
- webpackAsyncContext.id = ${JSON.stringify(id)};
532
- module.exports = webpackAsyncContext;`;
533
- }
534
-
535
- getSourceForEmptyContext(id) {
536
- return `function webpackEmptyContext(req) {
537
- var e = new Error('Cannot find module "' + req + '".');
538
- e.code = 'MODULE_NOT_FOUND';
539
- throw e;
540
- }
541
- webpackEmptyContext.keys = function() { return []; };
542
- webpackEmptyContext.resolve = webpackEmptyContext;
543
- module.exports = webpackEmptyContext;
544
- webpackEmptyContext.id = ${JSON.stringify(id)};`;
545
- }
546
-
547
- getSourceForEmptyAsyncContext(id) {
548
- return `function webpackEmptyAsyncContext(req) {
549
- // Here Promise.resolve().then() is used instead of new Promise() to prevent
550
- // uncaught exception popping up in devtools
551
- return Promise.resolve().then(function() {
552
- var e = new Error('Cannot find module "' + req + '".');
553
- e.code = 'MODULE_NOT_FOUND';
554
- throw e;
555
- });
556
- }
557
- webpackEmptyAsyncContext.keys = function() { return []; };
558
- webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
559
- module.exports = webpackEmptyAsyncContext;
560
- webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
561
- }
562
-
563
- getSourceString(asyncMode, runtimeTemplate) {
564
- if (asyncMode === "lazy") {
565
- if (this.blocks && this.blocks.length > 0) {
566
- return this.getLazySource(this.blocks, this.id);
567
- }
568
- return this.getSourceForEmptyAsyncContext(this.id);
569
- }
570
- if (asyncMode === "eager") {
571
- if (this.dependencies && this.dependencies.length > 0) {
572
- return this.getEagerSource(this.dependencies, this.id);
573
- }
574
- return this.getSourceForEmptyAsyncContext(this.id);
575
- }
576
- if (asyncMode === "lazy-once") {
577
- const block = this.blocks[0];
578
- if (block) {
579
- return this.getLazyOnceSource(
580
- block,
581
- block.dependencies,
582
- this.id,
583
- runtimeTemplate
584
- );
585
- }
586
- return this.getSourceForEmptyAsyncContext(this.id);
587
- }
588
- if (asyncMode === "async-weak") {
589
- if (this.dependencies && this.dependencies.length > 0) {
590
- return this.getAsyncWeakSource(this.dependencies, this.id);
591
- }
592
- return this.getSourceForEmptyAsyncContext(this.id);
593
- }
594
- if (asyncMode === "weak") {
595
- if (this.dependencies && this.dependencies.length > 0) {
596
- return this.getWeakSyncSource(this.dependencies, this.id);
597
- }
598
- }
599
- if (this.dependencies && this.dependencies.length > 0) {
600
- return this.getSyncSource(this.dependencies, this.id);
601
- }
602
- return this.getSourceForEmptyContext(this.id);
603
- }
604
-
605
- getSource(sourceString) {
606
- if (this.useSourceMap) {
607
- return new OriginalSource(sourceString, this.identifier());
608
- }
609
- return new RawSource(sourceString);
610
- }
611
-
612
- source(dependencyTemplates, runtimeTemplate) {
613
- return this.getSource(
614
- this.getSourceString(this.options.mode, runtimeTemplate)
615
- );
616
- }
617
-
618
- size() {
619
- // base penalty
620
- const initialSize = 160;
621
-
622
- // if we dont have dependencies we stop here.
623
- return this.dependencies.reduce(
624
- (size, dependency) => size + 5 + dependency.userRequest.length,
625
- initialSize
626
- );
627
- }
628
- }
629
-
630
- // TODO remove in webpack 5
631
- Object.defineProperty(ContextModule.prototype, "recursive", {
632
- configurable: false,
633
- get: util.deprecate(function() {
634
- return this.options.recursive;
635
- }, "ContextModule.recursive has been moved to ContextModule.options.recursive"),
636
- set: util.deprecate(function(value) {
637
- this.options.recursive = value;
638
- }, "ContextModule.recursive has been moved to ContextModule.options.recursive")
639
- });
640
-
641
- // TODO remove in webpack 5
642
- Object.defineProperty(ContextModule.prototype, "regExp", {
643
- configurable: false,
644
- get: util.deprecate(function() {
645
- return this.options.regExp;
646
- }, "ContextModule.regExp has been moved to ContextModule.options.regExp"),
647
- set: util.deprecate(function(value) {
648
- this.options.regExp = value;
649
- }, "ContextModule.regExp has been moved to ContextModule.options.regExp")
650
- });
651
-
652
- // TODO remove in webpack 5
653
- Object.defineProperty(ContextModule.prototype, "addon", {
654
- configurable: false,
655
- get: util.deprecate(function() {
656
- return this.options.addon;
657
- }, "ContextModule.addon has been moved to ContextModule.options.addon"),
658
- set: util.deprecate(function(value) {
659
- this.options.addon = value;
660
- }, "ContextModule.addon has been moved to ContextModule.options.addon")
661
- });
662
-
663
- // TODO remove in webpack 5
664
- Object.defineProperty(ContextModule.prototype, "async", {
665
- configurable: false,
666
- get: util.deprecate(function() {
667
- return this.options.mode;
668
- }, "ContextModule.async has been moved to ContextModule.options.mode"),
669
- set: util.deprecate(function(value) {
670
- this.options.mode = value;
671
- }, "ContextModule.async has been moved to ContextModule.options.mode")
672
- });
673
-
674
- // TODO remove in webpack 5
675
- Object.defineProperty(ContextModule.prototype, "chunkName", {
676
- configurable: false,
677
- get: util.deprecate(function() {
678
- return this.options.chunkName;
679
- }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName"),
680
- set: util.deprecate(function(value) {
681
- this.options.chunkName = value;
682
- }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName")
683
- });
684
-
685
- module.exports = ContextModule;
1
+ /*
2
+ MIT License http://www.opensource.org/licenses/mit-license.php
3
+ Author Tobias Koppers @sokra
4
+ */
5
+ "use strict";
6
+ const path = require("path");
7
+ const util = require("util");
8
+ const { OriginalSource, RawSource } = require("webpack-sources");
9
+ const Module = require("./Module");
10
+ const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
11
+ const Template = require("./Template");
12
+
13
+ class ContextModule extends Module {
14
+ // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"
15
+ // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp }
16
+ // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void
17
+ // options: ContextOptions
18
+ constructor(resolveDependencies, options) {
19
+ let resource;
20
+ let resourceQuery;
21
+ const queryIdx = options.resource.indexOf("?");
22
+ if (queryIdx >= 0) {
23
+ resource = options.resource.substr(0, queryIdx);
24
+ resourceQuery = options.resource.substr(queryIdx);
25
+ } else {
26
+ resource = options.resource;
27
+ resourceQuery = "";
28
+ }
29
+
30
+ super("javascript/dynamic", resource);
31
+
32
+ // Info from Factory
33
+ this.resolveDependencies = resolveDependencies;
34
+ this.options = Object.assign({}, options, {
35
+ resource: resource,
36
+ resourceQuery: resourceQuery
37
+ });
38
+ if (options.resolveOptions !== undefined)
39
+ this.resolveOptions = options.resolveOptions;
40
+
41
+ // Info from Build
42
+ this._contextDependencies = new Set([this.context]);
43
+
44
+ if (typeof options.mode !== "string")
45
+ throw new Error("options.mode is a required option");
46
+
47
+ this._identifier = this._createIdentifier();
48
+ }
49
+
50
+ updateCacheModule(module) {
51
+ this.resolveDependencies = module.resolveDependencies;
52
+ this.options = module.options;
53
+ this.resolveOptions = module.resolveOptions;
54
+ }
55
+
56
+ prettyRegExp(regexString) {
57
+ // remove the "/" at the front and the beginning
58
+ // "/foo/" -> "foo"
59
+ return regexString.substring(1, regexString.length - 1);
60
+ }
61
+
62
+ contextify(context, request) {
63
+ return request
64
+ .split("!")
65
+ .map(subrequest => {
66
+ let rp = path.relative(context, subrequest);
67
+ if (path.sep === "\\") rp = rp.replace(/\\/g, "/");
68
+ if (rp.indexOf("../") !== 0) rp = "./" + rp;
69
+ return rp;
70
+ })
71
+ .join("!");
72
+ }
73
+
74
+ _createIdentifier() {
75
+ let identifier = this.context;
76
+ if (this.options.resourceQuery)
77
+ identifier += ` ${this.options.resourceQuery}`;
78
+ if (this.options.mode) identifier += ` ${this.options.mode}`;
79
+ if (!this.options.recursive) identifier += " nonrecursive";
80
+ if (this.options.addon) identifier += ` ${this.options.addon}`;
81
+ if (this.options.regExp) identifier += ` ${this.options.regExp}`;
82
+ if (this.options.include) identifier += ` include: ${this.options.include}`;
83
+ if (this.options.exclude) identifier += ` exclude: ${this.options.exclude}`;
84
+ if (this.options.namespaceObject === "strict")
85
+ identifier += " strict namespace object";
86
+ else if (this.options.namespaceObject) identifier += " namespace object";
87
+
88
+ return identifier;
89
+ }
90
+
91
+ identifier() {
92
+ return this._identifier;
93
+ }
94
+
95
+ readableIdentifier(requestShortener) {
96
+ let identifier = requestShortener.shorten(this.context);
97
+ if (this.options.resourceQuery)
98
+ identifier += ` ${this.options.resourceQuery}`;
99
+ if (this.options.mode) identifier += ` ${this.options.mode}`;
100
+ if (!this.options.recursive) identifier += " nonrecursive";
101
+ if (this.options.addon)
102
+ identifier += ` ${requestShortener.shorten(this.options.addon)}`;
103
+ if (this.options.regExp)
104
+ identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`;
105
+ if (this.options.include)
106
+ identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`;
107
+ if (this.options.exclude)
108
+ identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`;
109
+ if (this.options.namespaceObject === "strict")
110
+ identifier += " strict namespace object";
111
+ else if (this.options.namespaceObject) identifier += " namespace object";
112
+
113
+ return identifier;
114
+ }
115
+
116
+ libIdent(options) {
117
+ let identifier = this.contextify(options.context, this.context);
118
+ if (this.options.mode) identifier += ` ${this.options.mode}`;
119
+ if (this.options.recursive) identifier += " recursive";
120
+ if (this.options.addon)
121
+ identifier += ` ${this.contextify(options.context, this.options.addon)}`;
122
+ if (this.options.regExp)
123
+ identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`;
124
+ if (this.options.include)
125
+ identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`;
126
+ if (this.options.exclude)
127
+ identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`;
128
+
129
+ return identifier;
130
+ }
131
+
132
+ needRebuild(fileTimestamps, contextTimestamps) {
133
+ const ts = contextTimestamps.get(this.context);
134
+ if (!ts) {
135
+ return true;
136
+ }
137
+
138
+ return ts >= this.buildInfo.builtTime;
139
+ }
140
+
141
+ build(options, compilation, resolver, fs, callback) {
142
+ this.built = true;
143
+ this.buildMeta = {};
144
+ this.buildInfo = {
145
+ builtTime: Date.now(),
146
+ contextDependencies: this._contextDependencies
147
+ };
148
+ this.resolveDependencies(fs, this.options, (err, dependencies) => {
149
+ if (err) return callback(err);
150
+
151
+ // abort if something failed
152
+ // this will create an empty context
153
+ if (!dependencies) {
154
+ callback();
155
+ return;
156
+ }
157
+
158
+ // enhance dependencies with meta info
159
+ for (const dep of dependencies) {
160
+ dep.loc = dep.userRequest;
161
+ dep.request = this.options.addon + dep.request;
162
+ }
163
+
164
+ if (this.options.mode === "sync" || this.options.mode === "eager") {
165
+ // if we have an sync or eager context
166
+ // just add all dependencies and continue
167
+ this.dependencies = dependencies;
168
+ } else if (this.options.mode === "lazy-once") {
169
+ // for the lazy-once mode create a new async dependency block
170
+ // and add that block to this context
171
+ if (dependencies.length > 0) {
172
+ const block = new AsyncDependenciesBlock(
173
+ this.options.chunkName,
174
+ this
175
+ );
176
+ for (const dep of dependencies) {
177
+ block.addDependency(dep);
178
+ }
179
+ this.addBlock(block);
180
+ }
181
+ } else if (
182
+ this.options.mode === "weak" ||
183
+ this.options.mode === "async-weak"
184
+ ) {
185
+ // we mark all dependencies as weak
186
+ for (const dep of dependencies) {
187
+ dep.weak = true;
188
+ }
189
+ this.dependencies = dependencies;
190
+ } else if (this.options.mode === "lazy") {
191
+ // if we are lazy create a new async dependency block per dependency
192
+ // and add all blocks to this context
193
+ let index = 0;
194
+ for (const dep of dependencies) {
195
+ let chunkName = this.options.chunkName;
196
+ if (chunkName) {
197
+ if (!/\[(index|request)\]/.test(chunkName)) chunkName += "[index]";
198
+ chunkName = chunkName.replace(/\[index\]/g, index++);
199
+ chunkName = chunkName.replace(
200
+ /\[request\]/g,
201
+ Template.toPath(dep.userRequest)
202
+ );
203
+ }
204
+ const block = new AsyncDependenciesBlock(
205
+ chunkName,
206
+ dep.module,
207
+ dep.loc,
208
+ dep.userRequest
209
+ );
210
+ block.addDependency(dep);
211
+ this.addBlock(block);
212
+ }
213
+ } else {
214
+ callback(
215
+ new Error(`Unsupported mode "${this.options.mode}" in context`)
216
+ );
217
+ return;
218
+ }
219
+ callback();
220
+ });
221
+ }
222
+
223
+ getUserRequestMap(dependencies) {
224
+ // if we filter first we get a new array
225
+ // therefor we dont need to create a clone of dependencies explicitly
226
+ // therefore the order of this is !important!
227
+ return dependencies
228
+ .filter(dependency => dependency.module)
229
+ .sort((a, b) => {
230
+ if (a.userRequest === b.userRequest) {
231
+ return 0;
232
+ }
233
+ return a.userRequest < b.userRequest ? -1 : 1;
234
+ })
235
+ .reduce((map, dep) => {
236
+ map[dep.userRequest] = dep.module.id;
237
+ return map;
238
+ }, Object.create(null));
239
+ }
240
+
241
+ getFakeMap(dependencies) {
242
+ if (!this.options.namespaceObject) return 1;
243
+ // if we filter first we get a new array
244
+ // therefor we dont need to create a clone of dependencies explicitly
245
+ // therefore the order of this is !important!
246
+ let hasNonHarmony = false;
247
+ let hasNamespace = false;
248
+ let hasNamed = false;
249
+ const fakeMap = dependencies
250
+ .filter(dependency => dependency.module)
251
+ .sort((a, b) => {
252
+ return b.module.id - a.module.id;
253
+ })
254
+ .reduce((map, dep) => {
255
+ const exportsType =
256
+ dep.module.buildMeta && dep.module.buildMeta.exportsType;
257
+ if (!exportsType) hasNonHarmony = true;
258
+ if (exportsType === "namespace") hasNamespace = true;
259
+ if (exportsType === "named") hasNamed = true;
260
+ map[dep.module.id] =
261
+ {
262
+ namespace: 1,
263
+ named: 2
264
+ }[exportsType] || 0;
265
+ return map;
266
+ }, Object.create(null));
267
+ if (!hasNamespace && hasNonHarmony && !hasNamed) return 0;
268
+ if (hasNamespace && !hasNonHarmony && !hasNamed) return 1;
269
+ if (!hasNamespace && !hasNonHarmony && hasNamed) return 2;
270
+ if (!hasNamespace && !hasNonHarmony && !hasNamed) return 1;
271
+ return fakeMap;
272
+ }
273
+
274
+ getFakeMapInitStatement(fakeMap) {
275
+ return typeof fakeMap === "object"
276
+ ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
277
+ : "";
278
+ }
279
+
280
+ getReturn(type) {
281
+ if (type === 1) return "module";
282
+ if (type === 2)
283
+ return 'Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module })';
284
+ if (type === 0) {
285
+ if (this.options.namespaceObject === "strict") {
286
+ return '/* fake namespace object */ { "default": module }';
287
+ } else {
288
+ return '(typeof module === "object" && module && module.__esModule ? module : Object.assign({/* fake namespace object */}, typeof module === "object" && module, { "default": module }))';
289
+ }
290
+ }
291
+ }
292
+
293
+ getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") {
294
+ if (typeof fakeMap === "number")
295
+ return `return ${this.getReturn(fakeMap)};`;
296
+ return `return ${fakeMapDataExpression} === 1 ? ${this.getReturn(
297
+ 1
298
+ )} : ${fakeMapDataExpression} ? ${this.getReturn(2)} : ${this.getReturn(
299
+ 0
300
+ )};`;
301
+ }
302
+
303
+ getSyncSource(dependencies, id) {
304
+ const map = this.getUserRequestMap(dependencies);
305
+ const fakeMap = this.getFakeMap(dependencies);
306
+ const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
307
+
308
+ return `var map = ${JSON.stringify(map, null, "\t")};
309
+ ${this.getFakeMapInitStatement(fakeMap)}
310
+
311
+ function webpackContext(req) {
312
+ var id = webpackContextResolve(req);
313
+ var module = __webpack_require__(id);
314
+ ${returnModuleObject}
315
+ }
316
+ function webpackContextResolve(req) {
317
+ var id = map[req];
318
+ if(!(id + 1)) { // check for number or string
319
+ var e = new Error('Cannot find module "' + req + '".');
320
+ e.code = 'MODULE_NOT_FOUND';
321
+ throw e;
322
+ }
323
+ return id;
324
+ }
325
+ webpackContext.keys = function webpackContextKeys() {
326
+ return Object.keys(map);
327
+ };
328
+ webpackContext.resolve = webpackContextResolve;
329
+ module.exports = webpackContext;
330
+ webpackContext.id = ${JSON.stringify(id)};`;
331
+ }
332
+
333
+ getWeakSyncSource(dependencies, id) {
334
+ const map = this.getUserRequestMap(dependencies);
335
+ const fakeMap = this.getFakeMap(dependencies);
336
+ const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
337
+
338
+ return `var map = ${JSON.stringify(map, null, "\t")};
339
+ ${this.getFakeMapInitStatement(fakeMap)}
340
+
341
+ function webpackContext(req) {
342
+ var id = webpackContextResolve(req);
343
+ if(!__webpack_require__.m[id]) {
344
+ var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
345
+ e.code = 'MODULE_NOT_FOUND';
346
+ throw e;
347
+ }
348
+ var module = __webpack_require__(id);
349
+ ${returnModuleObject}
350
+ }
351
+ function webpackContextResolve(req) {
352
+ var id = map[req];
353
+ if(!(id + 1)) { // check for number or string
354
+ var e = new Error('Cannot find module "' + req + '".');
355
+ e.code = 'MODULE_NOT_FOUND';
356
+ throw e;
357
+ }
358
+ return id;
359
+ }
360
+ webpackContext.keys = function webpackContextKeys() {
361
+ return Object.keys(map);
362
+ };
363
+ webpackContext.resolve = webpackContextResolve;
364
+ webpackContext.id = ${JSON.stringify(id)};
365
+ module.exports = webpackContext;`;
366
+ }
367
+
368
+ getAsyncWeakSource(dependencies, id) {
369
+ const map = this.getUserRequestMap(dependencies);
370
+ const fakeMap = this.getFakeMap(dependencies);
371
+ const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
372
+
373
+ return `var map = ${JSON.stringify(map, null, "\t")};
374
+ ${this.getFakeMapInitStatement(fakeMap)}
375
+
376
+ function webpackAsyncContext(req) {
377
+ return webpackAsyncContextResolve(req).then(function(id) {
378
+ if(!__webpack_require__.m[id]) {
379
+ var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
380
+ e.code = 'MODULE_NOT_FOUND';
381
+ throw e;
382
+ }
383
+ var module = __webpack_require__(id);
384
+ ${returnModuleObject}
385
+ });
386
+ }
387
+ function webpackAsyncContextResolve(req) {
388
+ // Here Promise.resolve().then() is used instead of new Promise() to prevent
389
+ // uncaught exception popping up in devtools
390
+ return Promise.resolve().then(function() {
391
+ var id = map[req];
392
+ if(!(id + 1)) { // check for number or string
393
+ var e = new Error('Cannot find module "' + req + '".');
394
+ e.code = 'MODULE_NOT_FOUND';
395
+ throw e;
396
+ }
397
+ return id;
398
+ });
399
+ }
400
+ webpackAsyncContext.keys = function webpackAsyncContextKeys() {
401
+ return Object.keys(map);
402
+ };
403
+ webpackAsyncContext.resolve = webpackAsyncContextResolve;
404
+ webpackAsyncContext.id = ${JSON.stringify(id)};
405
+ module.exports = webpackAsyncContext;`;
406
+ }
407
+
408
+ getEagerSource(dependencies, id) {
409
+ const map = this.getUserRequestMap(dependencies);
410
+ const fakeMap = this.getFakeMap(dependencies);
411
+ const thenFunction =
412
+ fakeMap !== 1
413
+ ? `function(id) {
414
+ var module = __webpack_require__(id);
415
+ ${this.getReturnModuleObjectSource(fakeMap)}
416
+ }`
417
+ : "__webpack_require__";
418
+ return `var map = ${JSON.stringify(map, null, "\t")};
419
+ ${this.getFakeMapInitStatement(fakeMap)}
420
+
421
+ function webpackAsyncContext(req) {
422
+ return webpackAsyncContextResolve(req).then(${thenFunction});
423
+ }
424
+ function webpackAsyncContextResolve(req) {
425
+ // Here Promise.resolve().then() is used instead of new Promise() to prevent
426
+ // uncaught exception popping up in devtools
427
+ return Promise.resolve().then(function() {
428
+ var id = map[req];
429
+ if(!(id + 1)) { // check for number or string
430
+ var e = new Error('Cannot find module "' + req + '".');
431
+ e.code = 'MODULE_NOT_FOUND';
432
+ throw e;
433
+ }
434
+ return id;
435
+ });
436
+ }
437
+ webpackAsyncContext.keys = function webpackAsyncContextKeys() {
438
+ return Object.keys(map);
439
+ };
440
+ webpackAsyncContext.resolve = webpackAsyncContextResolve;
441
+ webpackAsyncContext.id = ${JSON.stringify(id)};
442
+ module.exports = webpackAsyncContext;`;
443
+ }
444
+
445
+ getLazyOnceSource(block, dependencies, id, runtimeTemplate) {
446
+ const promise = runtimeTemplate.blockPromise({
447
+ block,
448
+ message: "lazy-once context"
449
+ });
450
+ const map = this.getUserRequestMap(dependencies);
451
+ const fakeMap = this.getFakeMap(dependencies);
452
+ const thenFunction =
453
+ fakeMap !== 1
454
+ ? `function(id) {
455
+ var module = __webpack_require__(id);
456
+ ${this.getReturnModuleObjectSource(fakeMap)};
457
+ }`
458
+ : "__webpack_require__";
459
+
460
+ return `var map = ${JSON.stringify(map, null, "\t")};
461
+ ${this.getFakeMapInitStatement(fakeMap)}
462
+
463
+ function webpackAsyncContext(req) {
464
+ return webpackAsyncContextResolve(req).then(${thenFunction});
465
+ }
466
+ function webpackAsyncContextResolve(req) {
467
+ return ${promise}.then(function() {
468
+ var id = map[req];
469
+ if(!(id + 1)) { // check for number or string
470
+ var e = new Error('Cannot find module "' + req + '".');
471
+ e.code = 'MODULE_NOT_FOUND';
472
+ throw e;
473
+ }
474
+ return id;
475
+ });
476
+ }
477
+ webpackAsyncContext.keys = function webpackAsyncContextKeys() {
478
+ return Object.keys(map);
479
+ };
480
+ webpackAsyncContext.resolve = webpackAsyncContextResolve;
481
+ webpackAsyncContext.id = ${JSON.stringify(id)};
482
+ module.exports = webpackAsyncContext;`;
483
+ }
484
+
485
+ getLazySource(blocks, id) {
486
+ let hasMultipleOrNoChunks = false;
487
+ const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0]));
488
+ const map = blocks
489
+ .filter(block => block.dependencies[0].module)
490
+ .map(block => ({
491
+ dependency: block.dependencies[0],
492
+ block: block,
493
+ userRequest: block.dependencies[0].userRequest
494
+ }))
495
+ .sort((a, b) => {
496
+ if (a.userRequest === b.userRequest) return 0;
497
+ return a.userRequest < b.userRequest ? -1 : 1;
498
+ })
499
+ .reduce((map, item) => {
500
+ const chunks =
501
+ (item.block.chunkGroup && item.block.chunkGroup.chunks) || [];
502
+ if (chunks.length !== 1) {
503
+ hasMultipleOrNoChunks = true;
504
+ }
505
+ const arrayStart = [item.dependency.module.id];
506
+ if (typeof fakeMap === "object")
507
+ arrayStart.push(fakeMap[item.dependency.module.id]);
508
+ map[item.userRequest] = arrayStart.concat(
509
+ chunks.map(chunk => chunk.id)
510
+ );
511
+
512
+ return map;
513
+ }, Object.create(null));
514
+
515
+ const chunksStartPosition = typeof fakeMap === "object" ? 2 : 1;
516
+ const requestPrefix = hasMultipleOrNoChunks
517
+ ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))`
518
+ : `__webpack_require__.e(ids[${chunksStartPosition}])`;
519
+ const returnModuleObject = this.getReturnModuleObjectSource(
520
+ fakeMap,
521
+ "ids[1]"
522
+ );
523
+
524
+ return `var map = ${JSON.stringify(map, null, "\t")};
525
+ function webpackAsyncContext(req) {
526
+ var ids = map[req];
527
+ if(!ids) {
528
+ return Promise.resolve().then(function() {
529
+ var e = new Error('Cannot find module "' + req + '".');
530
+ e.code = 'MODULE_NOT_FOUND';
531
+ throw e;
532
+ });
533
+ }
534
+ return ${requestPrefix}.then(function() {
535
+ var module = __webpack_require__(ids[0]);
536
+ ${returnModuleObject}
537
+ });
538
+ }
539
+ webpackAsyncContext.keys = function webpackAsyncContextKeys() {
540
+ return Object.keys(map);
541
+ };
542
+ webpackAsyncContext.id = ${JSON.stringify(id)};
543
+ module.exports = webpackAsyncContext;`;
544
+ }
545
+
546
+ getSourceForEmptyContext(id) {
547
+ return `function webpackEmptyContext(req) {
548
+ var e = new Error('Cannot find module "' + req + '".');
549
+ e.code = 'MODULE_NOT_FOUND';
550
+ throw e;
551
+ }
552
+ webpackEmptyContext.keys = function() { return []; };
553
+ webpackEmptyContext.resolve = webpackEmptyContext;
554
+ module.exports = webpackEmptyContext;
555
+ webpackEmptyContext.id = ${JSON.stringify(id)};`;
556
+ }
557
+
558
+ getSourceForEmptyAsyncContext(id) {
559
+ return `function webpackEmptyAsyncContext(req) {
560
+ // Here Promise.resolve().then() is used instead of new Promise() to prevent
561
+ // uncaught exception popping up in devtools
562
+ return Promise.resolve().then(function() {
563
+ var e = new Error('Cannot find module "' + req + '".');
564
+ e.code = 'MODULE_NOT_FOUND';
565
+ throw e;
566
+ });
567
+ }
568
+ webpackEmptyAsyncContext.keys = function() { return []; };
569
+ webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
570
+ module.exports = webpackEmptyAsyncContext;
571
+ webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`;
572
+ }
573
+
574
+ getSourceString(asyncMode, runtimeTemplate) {
575
+ if (asyncMode === "lazy") {
576
+ if (this.blocks && this.blocks.length > 0) {
577
+ return this.getLazySource(this.blocks, this.id);
578
+ }
579
+ return this.getSourceForEmptyAsyncContext(this.id);
580
+ }
581
+ if (asyncMode === "eager") {
582
+ if (this.dependencies && this.dependencies.length > 0) {
583
+ return this.getEagerSource(this.dependencies, this.id);
584
+ }
585
+ return this.getSourceForEmptyAsyncContext(this.id);
586
+ }
587
+ if (asyncMode === "lazy-once") {
588
+ const block = this.blocks[0];
589
+ if (block) {
590
+ return this.getLazyOnceSource(
591
+ block,
592
+ block.dependencies,
593
+ this.id,
594
+ runtimeTemplate
595
+ );
596
+ }
597
+ return this.getSourceForEmptyAsyncContext(this.id);
598
+ }
599
+ if (asyncMode === "async-weak") {
600
+ if (this.dependencies && this.dependencies.length > 0) {
601
+ return this.getAsyncWeakSource(this.dependencies, this.id);
602
+ }
603
+ return this.getSourceForEmptyAsyncContext(this.id);
604
+ }
605
+ if (asyncMode === "weak") {
606
+ if (this.dependencies && this.dependencies.length > 0) {
607
+ return this.getWeakSyncSource(this.dependencies, this.id);
608
+ }
609
+ }
610
+ if (this.dependencies && this.dependencies.length > 0) {
611
+ return this.getSyncSource(this.dependencies, this.id);
612
+ }
613
+ return this.getSourceForEmptyContext(this.id);
614
+ }
615
+
616
+ getSource(sourceString) {
617
+ if (this.useSourceMap) {
618
+ return new OriginalSource(sourceString, this.identifier());
619
+ }
620
+ return new RawSource(sourceString);
621
+ }
622
+
623
+ source(dependencyTemplates, runtimeTemplate) {
624
+ return this.getSource(
625
+ this.getSourceString(this.options.mode, runtimeTemplate)
626
+ );
627
+ }
628
+
629
+ size() {
630
+ // base penalty
631
+ const initialSize = 160;
632
+
633
+ // if we dont have dependencies we stop here.
634
+ return this.dependencies.reduce(
635
+ (size, dependency) => size + 5 + dependency.userRequest.length,
636
+ initialSize
637
+ );
638
+ }
639
+ }
640
+
641
+ // TODO remove in webpack 5
642
+ Object.defineProperty(ContextModule.prototype, "recursive", {
643
+ configurable: false,
644
+ get: util.deprecate(function() {
645
+ return this.options.recursive;
646
+ }, "ContextModule.recursive has been moved to ContextModule.options.recursive"),
647
+ set: util.deprecate(function(value) {
648
+ this.options.recursive = value;
649
+ }, "ContextModule.recursive has been moved to ContextModule.options.recursive")
650
+ });
651
+
652
+ // TODO remove in webpack 5
653
+ Object.defineProperty(ContextModule.prototype, "regExp", {
654
+ configurable: false,
655
+ get: util.deprecate(function() {
656
+ return this.options.regExp;
657
+ }, "ContextModule.regExp has been moved to ContextModule.options.regExp"),
658
+ set: util.deprecate(function(value) {
659
+ this.options.regExp = value;
660
+ }, "ContextModule.regExp has been moved to ContextModule.options.regExp")
661
+ });
662
+
663
+ // TODO remove in webpack 5
664
+ Object.defineProperty(ContextModule.prototype, "addon", {
665
+ configurable: false,
666
+ get: util.deprecate(function() {
667
+ return this.options.addon;
668
+ }, "ContextModule.addon has been moved to ContextModule.options.addon"),
669
+ set: util.deprecate(function(value) {
670
+ this.options.addon = value;
671
+ }, "ContextModule.addon has been moved to ContextModule.options.addon")
672
+ });
673
+
674
+ // TODO remove in webpack 5
675
+ Object.defineProperty(ContextModule.prototype, "async", {
676
+ configurable: false,
677
+ get: util.deprecate(function() {
678
+ return this.options.mode;
679
+ }, "ContextModule.async has been moved to ContextModule.options.mode"),
680
+ set: util.deprecate(function(value) {
681
+ this.options.mode = value;
682
+ }, "ContextModule.async has been moved to ContextModule.options.mode")
683
+ });
684
+
685
+ // TODO remove in webpack 5
686
+ Object.defineProperty(ContextModule.prototype, "chunkName", {
687
+ configurable: false,
688
+ get: util.deprecate(function() {
689
+ return this.options.chunkName;
690
+ }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName"),
691
+ set: util.deprecate(function(value) {
692
+ this.options.chunkName = value;
693
+ }, "ContextModule.chunkName has been moved to ContextModule.options.chunkName")
694
+ });
695
+
696
+ module.exports = ContextModule;