Skip to content

Commit f7c40dd

Browse files
fix: reach the url fallback for a chunk a second entrypoint has at startup
One `runtimeChunk` in front of two entrypoints makes a split chunk initial for the first and loadable by the second, so the loader's map leaves it unnamed while an id for it still arrives. Ask whether such a chunk can be loaded here rather than assuming an initial one never is. Also wrap `map`'s callback in the context module, whose index would otherwise be read as a fetch priority, and move the specifier shape to `util/identifier`.
1 parent dd063d2 commit f7c40dd

16 files changed

Lines changed: 147 additions & 27 deletions

File tree

‎lib/ContextModule.js‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1254,7 +1254,12 @@ module.exports = webpackAsyncContext;`;
12541254
const requestPrefix = hasNoChunk
12551255
? "Promise.resolve()"
12561256
: hasMultipleOrNoChunks
1257-
? `Promise.all(ids[${chunksPosition}].map(${RuntimeGlobals.ensureChunk}))`
1257+
? // Wrapped because `map` hands its callback an index too, which the loader
1258+
// would otherwise read as a fetch priority.
1259+
`Promise.all(ids[${chunksPosition}].map(${runtimeTemplate.returningFunction(
1260+
`${RuntimeGlobals.ensureChunk}(id)`,
1261+
"id"
1262+
)}))`
12581263
: `${RuntimeGlobals.ensureChunk}(ids[${chunksPosition}][0])`;
12591264
// Nothing loads a chunk when there is none to load.
12601265
if (!hasNoChunk) {

‎lib/RuntimeTemplate.js‎

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@ const { equals } = require("./util/ArrayHelpers");
3636
const { getScheme } = require("./util/URLAbsoluteSpecifier");
3737
const { compareIds } = require("./util/comparators");
3838
const compileBooleanMatcher = require("./util/compileBooleanMatcher");
39-
const { getUndoPath, toJsStringLiteral } = require("./util/identifier");
39+
const {
40+
RESOLVABLE_SPECIFIER_REGEXP,
41+
getUndoPath,
42+
toJsStringLiteral
43+
} = require("./util/identifier");
4044
const memoize = require("./util/memoize");
4145
const { propertyAccess, propertyName } = require("./util/property");
4246
const {
@@ -263,10 +267,6 @@ const ANALYZABLE_TOKEN_REGEXP = /\.\/@@webpackAnalyzableChunk:([\w-]+)@@/g;
263267
// The same token read back out of one quoted specifier.
264268
const ANALYZABLE_TOKEN_PAYLOAD = /@@webpackAnalyzableChunk:([\w-]+)@@/;
265269

266-
// What `import()` resolves as a place rather than as a package name: relative,
267-
// rooted, or carrying a scheme. Matched against the quote the specifier opens with.
268-
const RESOLVABLE_SPECIFIER = /^"(?:\.{0,2}\/|[a-zA-Z][\w+.-]*:)/;
269-
270270
// Stands in for the compilation hash inside an otherwise resolved filename, with the
271271
// requested length when the placeholder asked for one.
272272
const FULL_HASH_TOKEN_REGEXP = /@@webpackFullHash(?:-(\d+))?@@/g;
@@ -3771,16 +3771,37 @@ class RuntimeTemplate {
37713771
}
37723772

37733773
/**
3774-
* Whether the loader still needs to build a url from a chunk id: a chunk carrying
3775-
* a runtime of its own is reached by a static import and so is never named in the
3776-
* map, and only a runtime that can reach one has to keep the fallback.
3774+
* The chunks this loader can be handed an id for: the ones held by a group outside
3775+
* the initial wave, which is what an `import()` or a context map turns into an id.
3776+
* @param {Chunk} runtimeChunk the chunk holding the chunk loader
3777+
* @returns {Set<Chunk>} the chunks reachable from here through a non-initial group
3778+
*/
3779+
_loadableChunks(runtimeChunk) {
3780+
const queue = new Set(runtimeChunk.groupsIterable);
3781+
/** @type {Set<Chunk>} */
3782+
const chunks = new Set();
3783+
for (const group of queue) {
3784+
if (!group.isInitial()) {
3785+
for (const chunk of group.chunks) chunks.add(chunk);
3786+
}
3787+
for (const child of group.childrenIterable) queue.add(child);
3788+
}
3789+
return chunks;
3790+
}
3791+
3792+
/**
3793+
* Whether the loader still needs to build a url from a chunk id, which is the case
3794+
* for a chunk it can be asked for that `analyzableChunkImports` leaves unnamed: one
3795+
* carrying a runtime of its own, or one a second entrypoint has at startup.
37773796
* @param {Chunk} runtimeChunk the chunk holding the chunk loader
37783797
* @param {ChunkGraph} chunkGraph the chunk graph
37793798
* @returns {boolean} true when an id the map does not hold can reach the loader
37803799
*/
37813800
chunkImportsNeedRuntimeUrl(runtimeChunk, chunkGraph) {
3782-
for (const chunk of runtimeChunk.getAllReferencedChunks()) {
3783-
if (chunk === runtimeChunk || !chunk.hasRuntime()) continue;
3801+
const installed = new Set(runtimeChunk.getAllInitialChunks());
3802+
for (const chunk of this._loadableChunks(runtimeChunk)) {
3803+
if (chunk === runtimeChunk) continue;
3804+
if (!chunk.hasRuntime() && !installed.has(chunk)) continue;
37843805
if (JavascriptModulesPlugin.chunkHasJs(chunk, chunkGraph)) return true;
37853806
}
37863807
return false;
@@ -3843,7 +3864,7 @@ class RuntimeTemplate {
38433864
for (const [id, specifier] of specifiers) {
38443865
// A bare specifier is a package name, so spell it relative the way the
38453866
// runtime form's `.p + <file>` would have resolved it.
3846-
if (!RESOLVABLE_SPECIFIER.test(specifier)) {
3867+
if (!RESOLVABLE_SPECIFIER_REGEXP.test(specifier.slice(1))) {
38473868
specifiers.set(id, `"./${specifier.slice(1)}`);
38483869
}
38493870
}
@@ -4396,7 +4417,7 @@ class RuntimeTemplate {
43964417
// the chunk loader does. A literal part may still carry a stand-in of its own,
43974418
// so finish those here rather than scanning again.
43984419
return fillFullHash(
4399-
/^(?:\.{0,2}\/|[a-zA-Z][\w+.-]*:)/.test(specifier)
4420+
RESOLVABLE_SPECIFIER_REGEXP.test(specifier)
44004421
? specifier
44014422
: `./${specifier}`
44024423
);

‎lib/esm/ModuleChunkLoadingRuntimeModule.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ const { getInitialChunkIds } = require("../javascript/StartupHelpers");
1717
const { renderBaseUri } = require("../runtime/baseUri");
1818
const compileBooleanMatcher = require("../util/compileBooleanMatcher");
1919
const createHooksRegistry = require("../util/createHooksRegistry");
20+
const { RESOLVABLE_SPECIFIER_REGEXP } = require("../util/identifier");
2021
const memoize = require("../util/memoize");
2122

2223
const getAPIPlugin = memoize(() => require("../APIPlugin"));
@@ -159,7 +160,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
159160
publicPath === "auto"
160161
? JSON.stringify(rootOutputDir)
161162
: typeof publicPath === "string" &&
162-
!/^(?:\.{0,2}\/|[a-zA-Z][\w+.-]*:)/.test(publicPath) &&
163+
!RESOLVABLE_SPECIFIER_REGEXP.test(publicPath) &&
163164
!getAPIPlugin().usesRuntimePublicPathOverride(compilation)
164165
? `"./" + ${RuntimeGlobals.publicPath}`
165166
: RuntimeGlobals.publicPath;

‎lib/util/identifier.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ const WINDOWS_PATH_SEPARATOR_REGEXP = /\\/g;
1818
const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
1919
// A file URL, the form `import.meta.resolve()` returns a local module in.
2020
const FILE_URL_REGEXP = /^file:\/\//i;
21+
// What `import()` resolves as a place rather than as a package name: relative,
22+
// rooted, or carrying a scheme.
23+
const RESOLVABLE_SPECIFIER_REGEXP = /^(?:\.{0,2}\/|[a-zA-Z][\w+.-]*:)/;
2124

2225
/**
2326
* Converts a file URL to the path it names. Any other value is returned
@@ -582,6 +585,7 @@ const toJsStringLiteral = (str) =>
582585

583586
module.exports.ABSOLUTE_PATH_REGEXP = ABSOLUTE_PATH_REGEXP;
584587
module.exports.NODE_MODULES_REGEXP = NODE_MODULES_REGEXP;
588+
module.exports.RESOLVABLE_SPECIFIER_REGEXP = RESOLVABLE_SPECIFIER_REGEXP;
585589
module.exports.WINDOWS_ABS_PATH_REGEXP = WINDOWS_ABS_PATH_REGEXP;
586590
module.exports.WINDOWS_PATH_SEPARATOR_REGEXP = WINDOWS_PATH_SEPARATOR_REGEXP;
587591
module.exports.absolutify = absolutify;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import fs from "fs";
2+
import path from "path";
3+
4+
it("should load a chunk a second entrypoint already has at startup", async () => {
5+
const shared = await import("./shared.js");
6+
expect(shared.load()).toBe("shared");
7+
const lazy = await import("./lazy.js");
8+
expect(lazy.default).toBe("lazy");
9+
});
10+
11+
it("should keep the url fallback next to the names it can bake", () => {
12+
const source = fs.readFileSync(
13+
path.join(__STATS__.outputPath, "runtime.mjs"),
14+
"utf8"
15+
);
16+
17+
// Built at runtime so the needles are not source string literals here.
18+
expect(source).toContain(`${"chunkImports"} = {`);
19+
expect(source).toContain(`${"__webpack_require__"}.u(chunkId)`);
20+
});
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default "lazy";
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { load } from "./shared.js";
2+
3+
export default load();
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export function load() {
2+
return "shared";
3+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"use strict";
2+
3+
module.exports = {
4+
findBundle() {
5+
return "./bundle0.mjs";
6+
}
7+
};
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"use strict";
2+
3+
// `runtimeChunk` puts one loader in front of both entrypoints, so the chunk `splitChunks`
4+
// lifts out is one the first entry has at startup and the second asks the loader for.
5+
6+
/** @type {import("../../../../").Configuration} */
7+
module.exports = {
8+
target: "node",
9+
mode: "development",
10+
devtool: false,
11+
entry: {
12+
bundle0: "./index.js",
13+
other: "./other.js"
14+
},
15+
output: {
16+
module: true,
17+
filename: "[name].mjs",
18+
chunkFilename: "[name].mjs",
19+
publicPath: "auto"
20+
},
21+
optimization: {
22+
chunkIds: "named",
23+
runtimeChunk: "single",
24+
splitChunks: {
25+
cacheGroups: {
26+
shared: {
27+
test: /shared\.js/,
28+
name: "shared",
29+
chunks: "all",
30+
enforce: true
31+
}
32+
}
33+
}
34+
}
35+
};

0 commit comments

Comments
 (0)