Skip to content

Commit 7c272f1

Browse files
fix(css): preserve server style order for concurrent imports (#22913)
* fix(css): preserve server style order for concurrent imports * perf(css): shorten server style slot reservation --------- Co-authored-by: alexander-akait <[email protected]>
1 parent 55be23a commit 7c272f1

8 files changed

Lines changed: 127 additions & 16 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Preserve request order when collecting asynchronous CSS on the server.

‎lib/css/CssLoadingRuntimeModule.js‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -289,22 +289,28 @@ class CssLoadingRuntimeModule extends RuntimeModule {
289289
// collect it; never reject on a missing file
290290
const readCssFromDisk =
291291
withoutDocument || isNeutralPlatform
292-
? `Promise.all([import('fs'), import('url')]).then(${runtimeTemplate.basicFunction(
293-
"[{ readFile }, { URL }]",
294-
[
295-
`readFile(${runtimeTemplate.importMetaUrl("url")}, 'utf8', ${runtimeTemplate.basicFunction(
296-
"err, content",
297-
[
298-
`if (!err) ${runtimeTemplate.cssServerStyleRegistry()}["chunk-" + chunkId] = content;`,
299-
"loadingEnded({ type: 'load' });"
300-
]
301-
)});`
302-
]
303-
// No fs to import, or a url `readFile` rejects on sight (a CDN public
304-
// path): nothing to collect, which is what a missing file already means.
305-
)}).catch(${runtimeTemplate.expressionFunction(
306-
"loadingEnded({ type: 'load' })"
307-
)});`
292+
? Template.asString([
293+
`${cst} registry = ${runtimeTemplate.cssServerStyleRegistry()}, key = "chunk-" + chunkId;`,
294+
// Reserve request order before I/O without clearing another runtime's styles;
295+
// `||` only rewrites "" with "", so it matches an `undefined` check.
296+
`${runtimeTemplate.assignOr("registry[key]", '""')};`,
297+
`Promise.all([import('fs'), import('url')]).then(${runtimeTemplate.basicFunction(
298+
"[{ readFile }, { URL }]",
299+
[
300+
`readFile(${runtimeTemplate.importMetaUrl("url")}, 'utf8', ${runtimeTemplate.basicFunction(
301+
"err, content",
302+
[
303+
"if (!err) registry[key] = content;",
304+
"loadingEnded({ type: 'load' });"
305+
]
306+
)});`
307+
]
308+
// No fs to import, or a url `readFile` rejects on sight (a CDN public
309+
// path): nothing to collect, which is what a missing file already means.
310+
)}).catch(${runtimeTemplate.expressionFunction(
311+
"loadingEnded({ type: 'load' })"
312+
)});`
313+
])
308314
: "";
309315
const installedChunksObject = `{\n${Template.indent(
310316
Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
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: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
it("should collect concurrent stylesheets in request order", async () => {
2+
const previous = __webpack_css_server_styles__;
3+
const first = import(/* webpackChunkName: "first" */ "./first.css");
4+
const duplicate = import(/* webpackChunkName: "first" */ "./first.css");
5+
require("./injected.css");
6+
const second = import(/* webpackChunkName: "second" */ "./second.css");
7+
8+
const pendingCss = __webpack_css_server_styles__;
9+
10+
await Promise.all([first, duplicate, second]);
11+
12+
if (typeof document !== "undefined") {
13+
const links = document.getElementsByTagName("link");
14+
expect(links).toHaveLength(2);
15+
expect(links[0].href).toContain("/first.css");
16+
expect(links[1].href).toContain("/second.css");
17+
} else {
18+
if (previous) expect(pendingCss).toBe(previous);
19+
expect(pendingCss).toContain("color: blue");
20+
expect(pendingCss).not.toContain("undefined");
21+
const css = __webpack_css_server_styles__;
22+
expect(css).toContain("color: red");
23+
expect(css).toContain("color: green");
24+
expect(css.indexOf("color: red")).toBeLessThan(css.indexOf("color: blue"));
25+
expect(css.indexOf("color: blue")).toBeLessThan(css.indexOf("color: green"));
26+
await import("./first.css");
27+
expect(__webpack_css_server_styles__).toBe(css);
28+
}
29+
});
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
color: blue;
3+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
body {
2+
color: green;
3+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"use strict";
2+
3+
const fs = require("fs");
4+
const path = require("path");
5+
6+
/** @type {Map<string, () => void>} */
7+
const pending = new Map();
8+
9+
module.exports = {
10+
/**
11+
* @param {number} index configuration index
12+
* @returns {string[]} entries sharing the server style registry
13+
*/
14+
findBundle(index) {
15+
return [`bundle${index}-a.mjs`, `bundle${index}-b.mjs`];
16+
},
17+
modules: {
18+
fs: {
19+
/**
20+
* @param {import("fs").PathLike} filename stylesheet path
21+
* @param {BufferEncoding} encoding file encoding
22+
* @param {(error: NodeJS.ErrnoException | null, content: string) => void} callback read callback
23+
* @returns {void}
24+
*/
25+
readFile(filename, encoding, callback) {
26+
fs.readFile(filename, encoding, (error, content) => {
27+
pending.set(path.basename(String(filename)), () =>
28+
callback(error, content)
29+
);
30+
if (pending.size !== 2) return;
31+
const first = pending.get("first.css");
32+
const second = pending.get("second.css");
33+
pending.clear();
34+
second();
35+
first();
36+
});
37+
}
38+
}
39+
}
40+
};
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"use strict";
2+
3+
/** @type {import("../../../../").Configuration[]} */
4+
module.exports = ["universal", "node"].map((target, index) => ({
5+
mode: "development",
6+
target,
7+
devtool: false,
8+
entry: { a: "./index.js", b: "./index.js" },
9+
module: {
10+
generator: { css: { exportsOnly: false } },
11+
rules: [
12+
{ test: /injected\.css$/, type: "css", parser: { exportType: "style" } }
13+
]
14+
},
15+
output: {
16+
module: true,
17+
filename: `bundle${index}-[name].mjs`,
18+
cssChunkFilename: "[name].css",
19+
uniqueName: `css-server-styles-concurrent-${target}`
20+
},
21+
experiments: { css: true }
22+
}));

0 commit comments

Comments
 (0)