Skip to content

Commit d3e5a0b

Browse files
feat(css): add __webpack_css_server_styles__ to read server-collected CSS (#21576)
* feat: add `__webpack_css_server_styles__` to read server-collected CSS webpack already collects CSS into a global registry when the neutral platform runs without a DOM, but reading it meant scanning globalThis for an internal key derived from output.uniqueName. Expose the registry as a string through a module variable instead. Also route the registry through the __webpack_require__.g polyfill on targets without globalThis, so it works on the supported node baseline. * test: add a prerender case for `__webpack_css_server_styles__` Also regenerate types.d.ts, which went stale when the runtime global was reordered by lint. * fix(css): keep server-collected CSS in application order The no-DOM branch keyed the style registry by raw module id. Integer-like keys enumerate in ascending numeric order, so reading the registry back returned the styles sorted by module id instead of by the order they were applied, silently reversing the cascade. * test: cover the globalThis style registry branch Nothing built the server style registry with `environment.globalThis` enabled, so the direct-`globalThis` branch was never emitted. * docs: pair the runtime global doc comments with their exports An earlier lint autofix reordered the new export and left `getChunkUpdateScriptFilename` documented as the CSS reader. * fix: declare the require scope for the CSS server styles helper The helper assigns onto `__webpack_require__.cs`, but nothing pulled in the require scope, so a bundle whose only runtime consumer was `__webpack_css_server_styles__` threw before reaching the entry. The `globalThis` polyfill hid this whenever the target lacked `globalThis`.
1 parent 8a1e4ab commit d3e5a0b

29 files changed

Lines changed: 342 additions & 7 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Add the `__webpack_css_server_styles__` module variable to read the CSS collected while rendering without a DOM, and keep that CSS in the order the styles were applied.

‎lib/APIPlugin.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,12 @@ function getReplacements() {
107107
type: "string",
108108
assign: false
109109
},
110+
__webpack_css_server_styles__: {
111+
expr: `${RuntimeGlobals.getCssServerStyles}()`,
112+
req: [RuntimeGlobals.getCssServerStyles],
113+
type: "string",
114+
assign: false
115+
},
110116
__webpack_chunkname__: {
111117
expr: RuntimeGlobals.chunkName,
112118
req: [RuntimeGlobals.chunkName],

‎lib/RuntimeGlobals.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,13 @@ module.exports.getChunkUpdateCssFilename = "__webpack_require__.hk";
200200
*/
201201
module.exports.getChunkUpdateScriptFilename = "__webpack_require__.hu";
202202

203+
/**
204+
* function returning the CSS collected while rendering without a DOM as a
205+
* single string; empty when the styles went into the document instead
206+
* Arguments: () => string
207+
*/
208+
module.exports.getCssServerStyles = "__webpack_require__.cs";
209+
203210
/**
204211
* the webpack hash
205212
*/

‎lib/RuntimePlugin.js‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
const RuntimeGlobals = require("./RuntimeGlobals");
99
const { getPresentKinds } = require("./TemplatedPathPlugin");
10+
const CssServerStylesRuntimeModule = require("./css/CssServerStylesRuntimeModule");
1011
const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirementsDependency");
1112
const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
1213
const AsyncModuleGeneratorRuntimeModule = require("./runtime/AsyncModuleGeneratorRuntimeModule");
@@ -66,6 +67,7 @@ const GLOBALS_ON_REQUIRE = [
6667
RuntimeGlobals.definePropertyGetters,
6768
RuntimeGlobals.ensureChunk,
6869
RuntimeGlobals.entryModuleId,
70+
RuntimeGlobals.getCssServerStyles,
6971
RuntimeGlobals.getFullHash,
7072
RuntimeGlobals.global,
7173
RuntimeGlobals.makeNamespaceObject,
@@ -432,6 +434,20 @@ class RuntimePlugin {
432434
);
433435
return true;
434436
});
437+
compilation.hooks.runtimeRequirementInTree
438+
.for(RuntimeGlobals.getCssServerStyles)
439+
.tap(PLUGIN_NAME, (chunk, set) => {
440+
// The registry lives on the global, reached via the polyfill when
441+
// the target has no `globalThis`.
442+
if (!compilation.outputOptions.environment.globalThis) {
443+
set.add(RuntimeGlobals.global);
444+
}
445+
compilation.addRuntimeModule(
446+
chunk,
447+
new CssServerStylesRuntimeModule()
448+
);
449+
return true;
450+
});
435451
compilation.hooks.runtimeRequirementInTree
436452
.for(RuntimeGlobals.getUpdateManifestFilename)
437453
.tap(PLUGIN_NAME, (chunk, set) => {

‎lib/RuntimeTemplate.js‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -191,16 +191,21 @@ class RuntimeTemplate {
191191

192192
/**
193193
* Expression for the global registry that collects CSS server-side when there
194-
* is no DOM (SSR). An SSR host reads it from `globalThis`; it is keyed by the
195-
* style/chunk identifier and namespaced by `output.uniqueName`.
194+
* is no DOM (SSR). Read it with `__webpack_css_server_styles__`; it is keyed
195+
* by the style/chunk identifier and namespaced by `output.uniqueName`.
196+
* Targets without `globalThis` go through the `__webpack_require__.g`
197+
* polyfill, so consumers must also require `RuntimeGlobals.global`.
196198
* @returns {string} runtime expression evaluating to the registry object
197199
*/
198200
cssServerStyleRegistry() {
199201
const name = this.outputOptions.uniqueName;
200202
const key = JSON.stringify(
201203
name ? `__webpack_css__${name}` : "__webpack_css__"
202204
);
203-
return `(${this.assignOr(`globalThis[${key}]`, "{}")})`;
205+
const global = this.outputOptions.environment.globalThis
206+
? "globalThis"
207+
: RuntimeGlobals.global;
208+
return `(${this.assignOr(`${global}[${key}]`, "{}")})`;
204209
}
205210

206211
supportsConst() {

‎lib/css/CssInjectStyleRuntimeModule.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ class CssInjectStyleRuntimeModule extends RuntimeModule {
6363
? [
6464
"if (typeof document === 'undefined') {",
6565
Template.indent([
66-
`${runtimeTemplate.cssServerStyleRegistry()}[identifier] = css;`,
66+
// "module-" keeps numeric module ids from enumerating in ascending
67+
// order instead of the order the styles were applied in
68+
`${runtimeTemplate.cssServerStyleRegistry()}["module-" + identifier] = css;`,
6769
"return;"
6870
]),
6971
"}"
@@ -74,7 +76,7 @@ class CssInjectStyleRuntimeModule extends RuntimeModule {
7476
"if (typeof document === 'undefined') {",
7577
Template.indent([
7678
`${cst} styles = ${runtimeTemplate.cssServerStyleRegistry()};`,
77-
"for (var i = 0; i < identifiers.length; i++) delete styles[identifiers[i]];",
79+
'for (var i = 0; i < identifiers.length; i++) delete styles["module-" + identifiers[i]];',
7880
"return;"
7981
]),
8082
"}"

‎lib/css/CssModulesPlugin.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,13 @@ class CssModulesPlugin {
692692
onceForChunkSet.add(chunk);
693693
if (!isEnabledForChunk(chunk)) return;
694694

695+
// The neutral platform's no-DOM branch stores styles on the global.
696+
if (
697+
compilation.runtimeTemplate.isNeutralPlatform() &&
698+
!compilation.outputOptions.environment.globalThis
699+
) {
700+
set.add(RuntimeGlobals.global);
701+
}
695702
const CssLoadingRuntimeModule = getCssLoadingRuntimeModule();
696703
compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set));
697704
};
@@ -744,6 +751,13 @@ class CssModulesPlugin {
744751
.tap(PLUGIN_NAME, (chunk, set) => {
745752
// Same as above: namespace stub is enough.
746753
set.add(RuntimeGlobals.requireScope);
754+
// The neutral platform's no-DOM branch stores styles on the global.
755+
if (
756+
compilation.runtimeTemplate.isNeutralPlatform() &&
757+
!compilation.outputOptions.environment.globalThis
758+
) {
759+
set.add(RuntimeGlobals.global);
760+
}
747761
const CssInjectStyleRuntimeModule =
748762
getCssInjectStyleRuntimeModule();
749763
compilation.addRuntimeModule(
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const RuntimeGlobals = require("../RuntimeGlobals");
9+
const RuntimeModule = require("../RuntimeModule");
10+
const Template = require("../Template");
11+
12+
/** @typedef {import("../Compilation")} Compilation */
13+
14+
class CssServerStylesRuntimeModule extends RuntimeModule {
15+
constructor() {
16+
super("css server styles");
17+
}
18+
19+
/**
20+
* Generates runtime code for this runtime module.
21+
* @returns {string | null} runtime code
22+
*/
23+
generate() {
24+
const compilation = /** @type {Compilation} */ (this.compilation);
25+
const { runtimeTemplate } = compilation;
26+
const cst = runtimeTemplate.renderConst();
27+
28+
return Template.asString([
29+
`${RuntimeGlobals.getCssServerStyles} = ${runtimeTemplate.basicFunction(
30+
"",
31+
[
32+
`${cst} registry = ${runtimeTemplate.cssServerStyleRegistry()};`,
33+
'var css = "";',
34+
// keys are string-prefixed at the write site, so this yields
35+
// insertion order rather than ascending numeric module id order
36+
"for (var key in registry) css += registry[key];",
37+
"return css;"
38+
]
39+
)};`
40+
]);
41+
}
42+
}
43+
44+
module.exports = CssServerStylesRuntimeModule;

‎module.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ declare const __webpack_chunkname__: string;
215215
declare var __webpack_base_uri__: string;
216216
declare var __webpack_runtime_id__: string;
217217
declare const __webpack_hash__: string;
218+
declare const __webpack_css_server_styles__: string;
218219
declare const __webpack_modules__: Record<string | number, NodeJS.Module>;
219220
declare const __webpack_require__: (id: string | number) => unknown;
220221
declare var __webpack_chunk_load__: (chunkId: string | number) => Promise<void>;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// no CSS import: the module variable is the only thing pulling in runtime
2+
it("works when the collected styles are the only runtime consumer", () => {
3+
expect(__webpack_css_server_styles__).toBe("");
4+
});

0 commit comments

Comments
 (0)