Skip to content

Commit 12c35d7

Browse files
fix(analyzable): keep a runtime's url map under HMR and hint the served-both-ways fix
A hot update re-ships a runtime module whenever its generated code changes and runs it from the update chunk, so a map whose every url is spelled in full at code generation is never stale: it is written out under HMR too, and the runtime form is kept only for a name the fill spells or an update chunk at another depth. The served-both-ways bailout now names the public paths that need no base.
1 parent 964979d commit 12c35d7

22 files changed

Lines changed: 287 additions & 33 deletions

File tree

‎.changeset/006-analyzable-repair.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": patch
33
---
44

5-
Repair hashed names so cycles and [chunkhash] names bake in ESM output.
5+
Repair hashed names and keep baked url maps under HMR in ESM output.

‎lib/RuntimeTemplate.js‎

Lines changed: 65 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,14 @@ const RUNTIME_HASH_ROUND = 2;
206206

207207
// Why a public path needing a base could not be spelled from the chunk holding it.
208208
const SERVED_BAILOUT =
209-
"this module is in a chunk webpack loads through output.publicPath and in one it does not, so no one path back to the output root fits both";
209+
'this module is in a chunk webpack loads through output.publicPath and in one it does not, so no one path back to the output root fits both (a root-absolute or absolute output.publicPath, or "auto", is read the same from both)';
210+
211+
// Why a runtime's url map kept the runtime form under HMR: an update re-ships the
212+
// runtime module only when its own code changes, and runs it from the update chunk.
213+
const HOT_NAME_BAILOUT =
214+
"a hot update can move this name without changing the runtime module that spells it, so the update would not carry the new one";
215+
const HOT_DEPTH_BAILOUT =
216+
"a hot update runs the runtime module from output.hotUpdateChunkFilename, which sits at another depth than the runtime chunk";
210217

211218
/**
212219
* @import {
@@ -253,6 +260,7 @@ const CHUNK_SPECIFIER_PART_KINDS = new Set(["chunk", "cssChunk"]);
253260
const FULL_HASH_PART_KINDS = new Set(["publicPath", "template", "unserved"]);
254261

255262
// What the deferred pass scans for — the other half of what the class spells.
263+
const ANALYZABLE_TOKEN_PREFIX = "./@@webpackAnalyzableChunk:";
256264
const ANALYZABLE_TOKEN_REGEXP = /\.\/@@webpackAnalyzableChunk:([\w-]+)@@/g;
257265

258266
// Stands in for the compilation hash inside an otherwise resolved filename, with the
@@ -456,6 +464,8 @@ class RuntimeTemplate {
456464
this._publicPathShapeText = undefined;
457465
/** @type {string | null | undefined} */
458466
this._publicPathClimbText = undefined;
467+
/** @type {string | undefined} */
468+
this._hotUpdateUndoText = undefined;
459469
/** @type {WeakMap<Chunk, Placement>} */
460470
this._placementByChunk = new WeakMap();
461471
/** @type {Map<string, string | null | undefined>} */
@@ -3544,8 +3554,7 @@ class RuntimeTemplate {
35443554
* and the plugin declaring what it needs ask this, so the two always agree. The
35453555
* runtime hands an absolute url string to `link.href`, and so does this — the browser
35463556
* resolves the element against the document, which is not where the chunk sits, and
3547-
* the loader reads the url as text either way. Nothing is written out for a runtime
3548-
* that also carries the hot handler; see below.
3557+
* the loader reads the url as text either way.
35493558
* @param {Chunk} runtimeChunk the chunk holding the stylesheet loader
35503559
* @param {ChunkGraph} chunkGraph the chunk graph
35513560
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements what that chunk needs
@@ -3645,14 +3654,17 @@ class RuntimeTemplate {
36453654
sourceType,
36463655
runtimeRequirements
36473656
) {
3648-
// A map written now cannot answer for whatever id an update names, so it yields
3649-
// to HMR — analyzable output is what ships.
3650-
if (
3651-
runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers) ||
3652-
!this.supportsAnalyzable("url-runtime", chunkGraph, consumingModule)
3653-
) {
3657+
if (!this.supportsAnalyzable("url-runtime", chunkGraph, consumingModule)) {
36543658
return null;
36553659
}
3660+
// A hot update re-ships the runtime module only when its own code changes, and
3661+
// runs it from the update chunk: each url has to be spelled in full, from there.
3662+
const hot = runtimeRequirements.has(
3663+
RuntimeGlobals.hmrDownloadUpdateHandlers
3664+
);
3665+
if (hot && !this._hotUpdateKeepsDepth(consumingChunks)) {
3666+
return this._analyzableBailout(consumingModule, HOT_DEPTH_BAILOUT, null);
3667+
}
36563668
/** @type {Map<ChunkId, string>} */
36573669
const urls = new Map();
36583670
for (const chunk of chunks) {
@@ -3666,11 +3678,44 @@ class RuntimeTemplate {
36663678
sourceType
36673679
);
36683680
if (specifier === null) return null;
3681+
if (hot && RuntimeTemplate._isReservedSpecifier(specifier)) {
3682+
return this._analyzableBailout(consumingModule, HOT_NAME_BAILOUT, null);
3683+
}
36693684
urls.set(chunk.id, `${this.importMetaUrl(specifier)}.href`);
36703685
}
36713686
return urls.size > 0 ? urls : null;
36723687
}
36733688

3689+
/**
3690+
* Whether a literal depth written into these chunks is right from the hot update
3691+
* chunk too, which is where a hot update runs a re-shipped runtime module. A depth
3692+
* nothing settles here is spelled per asset by the fill, so it is right anywhere.
3693+
* @param {Chunk[]} chunks the chunks a runtime's url map is written into
3694+
* @returns {boolean} true when the update chunk sits at the same depth
3695+
*/
3696+
_hotUpdateKeepsDepth(chunks) {
3697+
if (this._hotUpdateUndoText === undefined) {
3698+
const { outputOptions } = this;
3699+
// Its hashes are neutralized as a chunk's are; the id is the chunk's own.
3700+
this._hotUpdateUndoText = getUndoPath(
3701+
this.compilation.getPath(
3702+
outputOptions.hotUpdateChunkFilename.replace(
3703+
HASH_IN_FILENAME_GLOBAL,
3704+
"x"
3705+
),
3706+
{ chunk: chunks[0] }
3707+
),
3708+
/** @type {string} */ (outputOptions.path),
3709+
true
3710+
);
3711+
}
3712+
for (const chunk of chunks) {
3713+
const { undo } = this._chunkPlacement(chunk);
3714+
if (undo !== null && undo !== this._hotUpdateUndoText) return false;
3715+
}
3716+
return true;
3717+
}
3718+
36743719
/**
36753720
* Static `new URL(<file>, import.meta.url)` for the binary emitted for an async wasm
36763721
* module. Only called when `supportsAnalyzable("wasm")` holds.
@@ -3874,13 +3919,23 @@ class RuntimeTemplate {
38743919
* @returns {string} the stand-in to emit
38753920
*/
38763921
_reserveAnalyzableSpecifier(parts) {
3877-
return `./@@webpackAnalyzableChunk:${Buffer.from(JSON.stringify(parts))
3922+
return `${ANALYZABLE_TOKEN_PREFIX}${Buffer.from(JSON.stringify(parts))
38783923
.toString("base64")
38793924
.replace(/\+/g, "-")
38803925
.replace(/\//g, "_")
38813926
.replace(/[=]/g, "")}@@`;
38823927
}
38833928

3929+
/**
3930+
* Whether a quoted specifier is a stand-in the deferred pass still has to spell,
3931+
* rather than text settled at code generation.
3932+
* @param {string} specifier a specifier already quoted
3933+
* @returns {boolean} true when it carries a stand-in
3934+
*/
3935+
static _isReservedSpecifier(specifier) {
3936+
return specifier.includes(ANALYZABLE_TOKEN_PREFIX);
3937+
}
3938+
38843939
/**
38853940
* Whether text still carries a compilation-hash stand-in, so nothing may be resolved
38863941
* against it here — the fill would land inside an already-resolved result.

‎test/configCases/analyzable/chunk-hint-href/hmr-entry.js‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,16 @@ it("should still hint with the hot handler present", async () => {
99
expect(a.default).toBe("a");
1010
});
1111

12-
it("should keep the runtime url form for a runtime that can be updated", () => {
12+
it("should write the hint urls out for a runtime that can be updated", () => {
1313
const bundle = fs.readFileSync(
1414
path.join(__STATS__.children[__INDEX__].outputPath, `${__NAME__}.mjs`),
1515
"utf8"
1616
);
1717

18-
// An update hints at ids this map knows nothing about, so nothing is written out.
19-
expect(bundle).not.toContain(`new URL("./${__NAME__}-a.mjs"`);
20-
expect(bundle).toContain(
21-
`link.href = ${"__webpack_require__"}.p + ${"__webpack_require__"}.u(chunkId);`
22-
);
18+
// Every url here is settled at build time, so an update that changes the map
19+
// re-ships the runtime module holding it, and the hint reads the map.
20+
expect(bundle).toContain(`new URL("./${__NAME__}-a.mjs"`);
21+
expect(bundle).toContain("link.href = chunkUrls[chunkId]();");
22+
// The hot handler still builds the update's url from the id.
23+
expect(bundle).toContain(`${"__webpack_require__"}.hu = `);
2324
});

‎test/configCases/analyzable/chunk-hint-href/webpack.config.js‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ module.exports = [
4949
// Reassigned where the hint runs, so no literal can name where the chunk is and the
5050
// runtime form has to stay.
5151
base(2, "override"),
52-
// The hot handler hints at whatever id an update names, so a runtime carrying it
53-
// keeps the runtime form rather than a map that knows only today's ids.
52+
// A hot update re-ships the runtime module whenever the map it holds changes, so
53+
// the map is written out here too.
5454
{
5555
...base(3, "hmr"),
5656
plugins: [

‎test/configCases/analyzable/css-chunk-href/hmr-entry.js‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,16 @@ it("should still load the stylesheet with the hot handler present", async () =>
1212
}
1313
});
1414

15-
it("should keep the runtime url form for a runtime that can be updated", () => {
15+
it("should write the stylesheet url out for a runtime that can be updated", () => {
1616
const bundle = fs.readFileSync(
1717
path.join(__STATS__.children[__INDEX__].outputPath, `${__NAME__}.mjs`),
1818
"utf8"
1919
);
2020

21-
// The hot path re-loads by whatever id an update names, which a map written at build
22-
// time knows nothing about, so nothing here is written out and the lookup ships.
23-
expect(bundle).not.toContain(`new URL("./${__NAME__}-lazy_css.css"`);
21+
// Every url here is settled at build time, so an update that changes the map
22+
// re-ships the runtime module holding it, and the loader reads the map.
23+
expect(bundle).toContain(`new URL("./${__NAME__}-lazy_css.css"`);
24+
expect(bundle).toContain("const url = cssUrls[chunkId]();");
25+
// The hot handler still re-loads a stylesheet by id, so the lookup ships for it.
2426
expect(bundle).toContain(`${"__webpack_require__"}.k = `);
25-
expect(bundle).toContain(`${"__webpack_require__"}.k(`);
2627
});

‎test/configCases/analyzable/css-chunk-href/webpack.config.js‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ module.exports = [
5151
// Reassigned where the chunk runs, so no literal can name where the stylesheet is
5252
// and the runtime form has to stay.
5353
base(2, "override", false),
54-
// The hot handler re-loads by whatever id an update names, so a runtime carrying it
55-
// keeps the runtime form everywhere rather than a map that knows only today's ids.
54+
// A hot update re-ships the runtime module whenever the map it holds changes, so
55+
// the map is written out here too.
5656
{
57-
...base(3, "hmr", false),
57+
...base(3, "hmr", true),
5858
plugins: [
5959
.../** @type {NonNullable<import("../../../../").Configuration["plugins"]>} */ (
60-
base(3, "hmr", false).plugins
60+
base(3, "hmr", true).plugins
6161
),
6262
new webpack.HotModuleReplacementPlugin()
6363
]
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import update from "../../update.esm";
2+
import { load } from "./styles";
3+
4+
import.meta.webpackHot.accept("./styles");
5+
6+
const hasStylesheet = (name) =>
7+
[...document.getElementsByTagName("link")].some(
8+
(link) => link.rel === "stylesheet" && link.href.endsWith(`/${name}`)
9+
);
10+
11+
it("should bake the stylesheet urls and follow a new one after an update", (done) => {
12+
load()
13+
.then(() => {
14+
expect(hasStylesheet("lazy_css.chunk.css")).toBe(true);
15+
// The loader reads the baked map rather than building a url from the id.
16+
const loader = __webpack_require__.f.css.toString();
17+
expect(loader).toContain("cssUrls[chunkId]()");
18+
expect(loader).not.toContain(".k(chunkId)");
19+
20+
NEXT(
21+
update(done, true, () => {
22+
import("./styles")
23+
.then((updated) => updated.load())
24+
.then(() => {
25+
expect(hasStylesheet("lazy2_css.chunk.css")).toBe(true);
26+
done();
27+
})
28+
.catch(done);
29+
})
30+
);
31+
})
32+
.catch(done);
33+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
color: red;
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
background: blue;
3+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
export const load = () => import("./lazy.css");
2+
---
3+
export const load = () =>
4+
Promise.all([import("./lazy.css"), import("./lazy2.css")]);

0 commit comments

Comments
 (0)