Skip to content

Commit dd2cf74

Browse files
fix(runtime): set up deferred imports only when a hot update needs them
Reach the module cache through __webpack_require__.c only in hot runtimes, and let the deferred namespace helper create its cache and mark evaluating modules itself, so builds without HMR or without deferred imports stay unchanged.
1 parent f5ee9b7 commit dd2cf74

13 files changed

Lines changed: 266 additions & 350 deletions

File tree

‎lib/hmr/HotModuleReplacementPlugin.js‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -967,11 +967,6 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
967967
runtimeRequirements.add(RuntimeGlobals.hmrDownloadUpdateHandlers);
968968
runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
969969
runtimeRequirements.add(RuntimeGlobals.moduleCache);
970-
if (compilation.options.experiments.deferImport) {
971-
runtimeRequirements.add(
972-
RuntimeGlobals.deferredModuleNamespaceCache
973-
);
974-
}
975970
compilation.addRuntimeModule(
976971
chunk,
977972
new HotModuleReplacementRuntimeModule()

‎lib/javascript/JavascriptModulesPlugin.js‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1726,6 +1726,13 @@ class JavascriptModulesPlugin {
17261726
// object before evaluation.
17271727
buf.push("// The deferred module cache");
17281728
buf.push(`${bootstrapCst} __webpack_module_deferred_exports__ = {};`);
1729+
// Every defer-import site for one module must yield the same Deferred
1730+
// Module Namespace, distinct from any eager one, so the proxy is cached
1731+
// here for call sites in different files to share.
1732+
buf.push("// The deferred namespace cache");
1733+
buf.push(
1734+
`${bootstrapCst} __webpack_module_deferred_namespace_cache__ = {};`
1735+
);
17291736
buf.push("");
17301737
}
17311738

@@ -1756,12 +1763,6 @@ class JavascriptModulesPlugin {
17561763
buf.push("");
17571764
}
17581765

1759-
if (runtimeRequirements.has(RuntimeGlobals.deferredModuleNamespaceCache)) {
1760-
buf.push("// The deferred namespace cache, shared with hot updates");
1761-
buf.push(`${RuntimeGlobals.deferredModuleNamespaceCache} = {};`);
1762-
buf.push("");
1763-
}
1764-
17651766
if (interceptModuleExecution) {
17661767
buf.push("// expose the module execution interceptor");
17671768
buf.push(`${RuntimeGlobals.interceptModuleExecution} = [];`);
@@ -2186,8 +2187,6 @@ class JavascriptModulesPlugin {
21862187
// skips the deferred exports object, hence the separate flag.
21872188
const needModuleDeferAny =
21882189
needModuleDefer ||
2189-
// Hot updates may introduce deferred imports after this bootstrap runs.
2190-
runtimeRequirements.has(RuntimeGlobals.deferredModuleNamespaceCache) ||
21912190
runtimeRequirements.has(
21922191
RuntimeGlobals.makeOptimizedDeferredNamespaceObject
21932192
);

‎lib/runtime/AsyncModuleRuntimeModule.js‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
3333
const fn = RuntimeGlobals.asyncModule;
3434
const defer = this._deferInterop;
3535
const strictErrors = this._strictModuleErrorHandling;
36+
const moduleCache = this.receivesHotUpdates()
37+
? RuntimeGlobals.moduleCache
38+
: "__webpack_module_cache__";
3639
const rejectCall = "reject(promise[webpackError] = err)";
3740
const rejectExpression = strictErrors
3841
? `(markCycle(err), ${rejectCall})`
@@ -65,7 +68,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
6568
Template.indent([
6669
`${cst} hasUnresolvedAsyncSubgraph = asyncDeps.some((id) => {`,
6770
Template.indent([
68-
`${cst} cache = ${RuntimeGlobals.moduleCache}[id];`,
71+
`${cst} cache = ${moduleCache}[id];`,
6972
"if (!cache) return true;",
7073
// A cached entry no longer means finished, and a rejected
7174
// one is done but its error must still reach the importer.
@@ -223,7 +226,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule {
223226
`group && group.forEach(${runtimeTemplate.basicFunction(
224227
"id",
225228
[
226-
`${cst} peer = ${RuntimeGlobals.moduleCache}[id];`,
229+
`${cst} peer = ${moduleCache}[id];`,
227230
"if (peer && peer.error === undefined) peer.error = err;"
228231
]
229232
)})`,

‎lib/runtime/HelperRuntimeModule.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,12 @@
44

55
"use strict";
66

7+
const RuntimeGlobals = require("./RuntimeGlobals");
78
const RuntimeModule = require("./RuntimeModule");
89

10+
/** @import Chunk from "../graph/Chunk" */
11+
/** @import ChunkGraph from "../graph/ChunkGraph" */
12+
913
/**
1014
* Base class for runtime modules that only emit helper functions and do not
1115
* need special staging or attachment behavior beyond `RuntimeModule`.
@@ -28,6 +32,17 @@ class HelperRuntimeModule extends RuntimeModule {
2832
// A helper defines a function on the require global and nothing else.
2933
return RuntimeModule.NO_CHUNK_HANDLERS;
3034
}
35+
36+
/**
37+
* Whether a hot update can deliver this helper, which then runs outside the
38+
* bootstrap scope and reaches its state only through `__webpack_require__`.
39+
* @returns {boolean} true, when the runtime accepts hot updates
40+
*/
41+
receivesHotUpdates() {
42+
return /** @type {ChunkGraph} */ (this.chunkGraph)
43+
.getTreeRuntimeRequirements(/** @type {Chunk} */ (this.chunk))
44+
.has(RuntimeGlobals.hmrDownloadManifest);
45+
}
3146
}
3247

3348
module.exports = HelperRuntimeModule;

‎lib/runtime/MakeDeferredNamespaceObjectRuntime.js‎

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const HelperRuntimeModule = require("./HelperRuntimeModule");
1010
const RuntimeGlobals = require("./RuntimeGlobals");
1111

1212
/** @import { ModuleId } from "../graph/ChunkGraph" */
13+
/** @import RuntimeTemplate from "../template/RuntimeTemplate" */
1314
/** @import Module, { RuntimeRequirements, ExportsType } from "../module/Module" */
1415
/** @import ModuleGraph from "../graph/ModuleGraph" */
1516

@@ -221,6 +222,36 @@ function getOptimizedDeferredModule(
221222
)})`;
222223
}
223224

225+
/**
226+
* Renders the setup a deferred namespace helper needs when a hot update delivers
227+
* it, since the running bootstrap may not mark modules as evaluating.
228+
* @param {RuntimeTemplate} runtimeTemplate the runtime template
229+
* @returns {string} setup code, run once per runtime
230+
*/
231+
function renderHotDeferredSetup(runtimeTemplate) {
232+
const cache = RuntimeGlobals.deferredModuleNamespaceCache;
233+
return Template.asString([
234+
// The namespace cache doubles as the flag that the interceptor is installed.
235+
`if (!${cache}) {`,
236+
Template.indent([
237+
`${cache} = {};`,
238+
`${RuntimeGlobals.interceptModuleExecution}.push(${runtimeTemplate.basicFunction(
239+
"options",
240+
[
241+
`${runtimeTemplate.renderConst()} factory = options.factory;`,
242+
"if (factory) options.factory = function(module) {",
243+
Template.indent([
244+
"module.evaluating = true;",
245+
"try { return factory.apply(this, arguments); } finally { module.evaluating = false; }"
246+
]),
247+
"};"
248+
]
249+
)});`
250+
]),
251+
"}"
252+
]);
253+
}
254+
224255
class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
225256
/**
226257
* Returns true, if the runtime module should get it's own scope.
@@ -252,7 +283,12 @@ class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeMod
252283
const lt = runtimeTemplate.renderLet();
253284
const fn = RuntimeGlobals.makeOptimizedDeferredNamespaceObject;
254285
const hasAsync = this.hasAsyncRuntime;
286+
const hot = this.receivesHotUpdates();
287+
const moduleCache = hot
288+
? RuntimeGlobals.moduleCache
289+
: "__webpack_module_cache__";
255290
return Template.asString([
291+
...(hot ? [renderHotDeferredSetup(runtimeTemplate)] : []),
256292
// Note: must be a function (not arrow), because this is used in body!
257293
// `asyncDeps` keeps a fixed positional slot even without async runtime
258294
// so the trailing `syncDeps` (defer-cycle closure) always lines up.
@@ -267,11 +303,11 @@ class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeMod
267303
// Forcing a module that is already evaluating, a cycle reached
268304
// through a deferred import, must throw rather than expose partial
269305
// exports. `syncDeps` carries the closure that catches it first.
270-
`${cst} cachedModule = ${RuntimeGlobals.moduleCache}[moduleId];`,
306+
`${cst} cachedModule = ${moduleCache}[moduleId];`,
271307
'if (cachedModule !== undefined && (cachedModule.evaluating || cachedModule.evaluatingAsync)) throw new TypeError("Cannot access a deferred module namespace while the module is being evaluated");',
272308
"if (syncDeps) for (var i = 0; i < syncDeps.length; i++) {",
273309
Template.indent([
274-
`${cst} depModule = ${RuntimeGlobals.moduleCache}[syncDeps[i]];`,
310+
`${cst} depModule = ${moduleCache}[syncDeps[i]];`,
275311
'if (depModule !== undefined && (depModule.evaluating || depModule.evaluatingAsync)) throw new TypeError("Cannot access a deferred module namespace while a dependency is being evaluated");'
276312
]),
277313
"}",
@@ -294,7 +330,7 @@ class MakeOptimizedDeferredNamespaceObjectRuntimeModule extends HelperRuntimeMod
294330
`if(isAsync) obj[${RuntimeGlobals.deferredModuleAsyncTransitiveDependenciesSymbol}] = asyncDeps.filter(${runtimeTemplate.basicFunction(
295331
"id",
296332
[
297-
`${cst} dep = ${RuntimeGlobals.moduleCache}[id];`,
333+
`${cst} dep = ${moduleCache}[id];`,
298334
"if (dep && dep.evaluating) return false;",
299335
"r(id);",
300336
"return true;"
@@ -350,7 +386,14 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
350386
const sealed = this.sealed;
351387
const synthesized = this.synthesized;
352388
const init = `${runtimeTemplate.optionalChaining("init", "()")};`;
353-
return `${fn} = ${runtimeTemplate.basicFunction(
389+
const hot = this.receivesHotUpdates();
390+
const moduleCache = hot
391+
? RuntimeGlobals.moduleCache
392+
: "__webpack_module_cache__";
393+
const namespaceCache = hot
394+
? RuntimeGlobals.deferredModuleNamespaceCache
395+
: "__webpack_module_deferred_namespace_cache__";
396+
return `${hot ? `${renderHotDeferredSetup(runtimeTemplate)}\n` : ""}${fn} = ${runtimeTemplate.basicFunction(
354397
"moduleId, mode, exportNames",
355398
[
356399
// WHY: the TC39 import-defer spec makes a deferred namespace distinct
@@ -373,12 +416,10 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
373416
sealed && synthesized
374417
? "if (!(mode & 8)) exportNames = undefined;"
375418
: "",
376-
`${lt} byMode = ${RuntimeGlobals.deferredModuleNamespaceCache}[moduleId];`,
419+
`${lt} byMode = ${namespaceCache}[moduleId];`,
377420
"if (byMode && byMode[mode] !== undefined) return byMode[mode];",
378-
`if (!byMode) byMode = ${RuntimeGlobals.deferredModuleNamespaceCache}[moduleId] = {};`,
379-
synthesized
380-
? `${cst} cachedModule = ${RuntimeGlobals.moduleCache}[moduleId];`
381-
: "",
421+
`if (!byMode) byMode = ${namespaceCache}[moduleId] = {};`,
422+
synthesized ? `${cst} cachedModule = ${moduleCache}[moduleId];` : "",
382423
synthesized
383424
? "if (cachedModule && cachedModule.error === undefined && !(mode & 8)) {"
384425
: "",
@@ -397,7 +438,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule {
397438
// A deferred namespace that forces evaluation of a module that is
398439
// already evaluating (a cycle) must throw rather than expose its
399440
// partial exports.
400-
`${cst} evaluatingModule = ${RuntimeGlobals.moduleCache}[moduleId];`,
441+
`${cst} evaluatingModule = ${moduleCache}[moduleId];`,
401442
'if (evaluatingModule !== undefined && (evaluatingModule.evaluating || evaluatingModule.evaluatingAsync)) throw new TypeError("Cannot access a deferred module namespace while the module is being evaluated");',
402443
`ns = ${RuntimeGlobals.require}(moduleId);`,
403444
hasAsync

‎lib/runtime/RuntimeGlobals.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ module.exports.deferredModuleAsyncTransitiveDependenciesSymbol =
122122
"__webpack_require__.zS";
123123

124124
/**
125-
* cached deferred namespaces, shared across runtime updates
125+
* cached deferred namespaces, kept on `__webpack_require__` when hot updates can replace their helper
126126
*/
127127
module.exports.deferredModuleNamespaceCache = "__webpack_require__.zC";
128128

‎lib/runtime/RuntimePlugin.js‎

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,6 @@ const GLOBALS_ON_REQUIRE = [
171171
RuntimeGlobals.onChunksLoaded,
172172
RuntimeGlobals.makeOptimizedDeferredNamespaceObject,
173173
RuntimeGlobals.makeDeferredNamespaceObject,
174-
RuntimeGlobals.deferredModuleNamespaceCache,
175174
RuntimeGlobals.concatenationWrap,
176175
RuntimeGlobals.constructRequire
177176
];
@@ -195,14 +194,11 @@ const TREE_DEPENDENCIES = {
195194
RuntimeGlobals.asyncModule
196195
],
197196
[RuntimeGlobals.makeOptimizedDeferredNamespaceObject]: [
198-
RuntimeGlobals.require,
199-
RuntimeGlobals.moduleCache
197+
RuntimeGlobals.require
200198
],
201199
[RuntimeGlobals.makeDeferredNamespaceObject]: [
202200
RuntimeGlobals.createFakeNamespaceObject,
203-
RuntimeGlobals.require,
204-
RuntimeGlobals.moduleCache,
205-
RuntimeGlobals.deferredModuleNamespaceCache
201+
RuntimeGlobals.require
206202
],
207203
[RuntimeGlobals.initializeSharing]: [RuntimeGlobals.shareScopeMap],
208204
[RuntimeGlobals.shareScopeMap]: [RuntimeGlobals.hasOwnProperty],
@@ -422,14 +418,8 @@ class RuntimePlugin {
422418
});
423419
compilation.hooks.runtimeRequirementInTree
424420
.for(RuntimeGlobals.asyncModule)
425-
.tap(PLUGIN_NAME, (chunk, set) => {
421+
.tap(PLUGIN_NAME, (chunk) => {
426422
const experiments = compilation.options.experiments;
427-
if (
428-
experiments.deferImport ||
429-
compilation.outputOptions.strictModuleErrorHandling
430-
) {
431-
set.add(RuntimeGlobals.moduleCache);
432-
}
433423
compilation.addLazyRuntimeModule(
434424
chunk,
435425
getAsyncModuleRuntimeModule,

0 commit comments

Comments
 (0)