Skip to content

Commit 70f8a56

Browse files
feat(css): minify custom-property whitespace, merge longhands past a nested rule (#21773)
* feat(css): minify the whitespace between a custom property's tokens A custom property's tokens are the value the CSSOM hands back, so none of them is rewritten — but the whitespace between two of them only says they are two. A run of it is now the one space they need, and nothing at all where a comma or a block edge already parts them. Also folds the two spaces a dropped comment used to leave into one, and teaches the equivalence oracle that whitespace beside `[]` / `{}` is as insignificant as beside `()`, which it already normalized. * feat(css): merge a longhand family in a block that holds a nested rule The merge was skipped for the whole block as soon as it held one child rule, because a rule between two longhands would be stepped over and the adjacency scan reads declarations only. Count the child rules standing before each declaration instead, so only a rule *inside* a family's span blocks that family — a nested `@supports` re-declaring a longhand still does, one standing after the four no longer does. Costs nothing where it cannot pay: the counts are built only once a block is known to hold two mergeable longhand names. * fix(css): drop a shadow's trailing zero written with a unit `_dropShadowZeroLengths` reads the components as authored — the zero-unit drop prints later — but tested them against the bare string "0", so `box-shadow:0 0 0 0 red` collapsed and `box-shadow:0px 0px 0px 0px red` did not. Whether the collapse ran came down to which spelling the author happened to use. Test the components with `_isZeroLength`, which is what the rest of the printer already asks. `0%` stays a percentage, which a shadow's <length> slots do not take. * docs(css): record why a string's hex escape is left as written csso and lightningcss write the character a hex escape names. It is value-identical, so the reason not to follow them is a measurement: over 19 framework stylesheets it saves 6420 raw bytes and costs 593 gzip ones, because an escape is a repetitive ASCII alphabet where the character is a 3-byte UTF-8 run. The benchmark says the same from the other side — on Font Awesome lightningcss is 3.8 KB smaller raw and 0.3 KB bigger gzipped. Written next to `_minifyString`, where the change would be made, and pinned by two configCases lines. * docs: state which size column a change is accepted on The guide already observed that raw and compressed bytes disagree; it never said which one decides. Make it a rule: gzip decides, raw is the tiebreak, and the seam they part along is removing information (shrinks both, always) against re-encoding it (has to show a compressed win). Both refusals webpack ships on size grounds — convertLengthUnits, and leaving a string's hex escape as written — sit on the re-encoding side, so the rule is descriptive of what is already there rather than new policy. * build: report the deciding size column in the size tools All three tools already measured raw/gzip/brotli/zstd; what they led with was raw, which is the column a change should not be accepted on. Code Size report: the verdict table gains `Gzip change` and `Gzip new/gone` beside the raw pair, the per-asset compressed columns carry bytes as well as a percentage (a real move on a small asset rounds to 0.00%, and percentages do not add up across rows), and the row budget ranks on whichever of raw and gzip moved further so a re-encoding that barely moves raw cannot be truncated away. Both minifier benchmarks: `saved` now reads off gzip and sits beside it; raw stays first as the tiebreak. The stored report shape is unchanged — gzip was always in it — so an existing baseline stays comparable and REPORT_VERSION does not move. * fix(css): mark a size row by gzip, and close up custom-property blocks Addresses the review on #21773. The Code Size row marker read `delta.raw` first, so an asset that lost a raw byte and gained a gzip one printed 🟢 — which the report on this very pull request did, for `minimize-lightningcss-values`. It follows gzip now, with raw the tiebreak. A custom property kept the whitespace beside a block delimiter although nothing fuses across one, so `a [b] c` stayed as written where `foo( 1 )` already closed up. Both sides of `[`, `{`, `)`, `]` and `}` now go; `(` is the exception, since an identifier in front of it makes a function token, and `_wouldFuseTokens` still wins wherever it applies. Also: AGENTS.md no longer claims removing bytes always shrinks gzip — it does not, and `css/minimize bundle0.css` in this pull request's own size report is the counterexample (raw -1 B, zstd +1 B); the changeset is back under 80 characters; and thirteen comments are trimmed to the two lines the guide asks for. * docs: reword the block-boundary fixture note and tighten the size rule Addresses the second review on #21773. The fixture's kept comment read `bar \`(\`, which an identifier in front of turns into a function token`, which parses badly; it now says what it means. The removal-vs-re-encoding bullet is tightened — it grew a clause when the previous round asked for the "always" to be qualified.
1 parent 2502bbd commit 70f8a56

19 files changed

Lines changed: 357 additions & 122 deletions

File tree

‎.changeset/075-css-minify-values-and-rules.md‎

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

5-
Minify CSS values, shorthands, rules, named layers and vendor spellings further.
5+
Minify more CSS: values, shorthands, rules, layers, vendor spellings, spacing.

‎AGENTS.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,15 @@ A claim about **webpack's CSS or HTML minifier versus the ecosystem's** (size, s
274274

275275
A claim about the **size of what webpack emits** is the counting kind, and `yarn test:size` is how it is counted: it builds every `configCases/` case with the defaults a user gets and reports the raw/gzip/brotli/zstd size of every asset, so a change to `lib/runtime/` or to a dependency template shows up as bytes on the wire. Compare two runs with `--baseline <report>`; the `Code Size` CI job does the same against the report `main` last uploaded and comments the diff on the pull request.
276276

277+
**Which column decides it: gzip. Raw is the tiebreak, never the case on its own.** Compressed bytes are what crosses the wire, and gzip is the floor every client gets where brotli and zstd are subsets of it — so where the compressed columns disagree with each other, the one saying "no" wins and the change has to earn its way in. Raw still buys real decompress, parse and memory, so a change that is compressed-neutral and cuts raw is worth taking; one that cuts raw and grows gzip is not, whatever the raw number looks like.
278+
279+
The two columns disagree along one seam, and knowing which side a change is on saves measuring it:
280+
281+
- **Removing information** — a dead rule, a duplicate declaration, a longhand its shorthand implies, whitespace, a comment — shrinks raw and normally the compressed columns with it, so it needs no routine check. Not a guarantee: a small removal can delete a run a later match pointed back to, so read the compressed column when the removal is small.
282+
- **Re-encoding it** — swapping one spelling for a shorter one — is where they part, because a compressor rewards repetition and a short-but-novel token widens the literal alphabet. **A re-encoding has to show a compressed win to be worth taking.** Both of the refusals webpack ships on size grounds rather than correctness ones are this shape: `output.environment.convertLengthUnits` (`16px` → `1pc`) is off by default because it earns nothing compressed, and a string's hex escape is left as written because writing the character it names saves 6422 raw bytes and costs 595 gzip ones over the `benchmark:css-minifiers` fixtures — the same trade that makes a rival 3.8 KB smaller raw on Font Awesome and 0.3 KB bigger gzipped.
283+
284+
This is a rule for which number a change is accepted on at review time, not something a printer can consult: no minifier runs a compressor in its inner loop, and neither should ours.
285+
277286
Pitfalls that have produced wrong conclusions here:
278287

279288
- **Micro-benchmarks of one function lie.** V8's escape analysis deletes non-escaping allocations and the compilation cache hides repeated `new Function` cost. Measure inside a real build.
@@ -580,9 +589,9 @@ Code that emits runtime into the bundle — chunk loading (`lib/web/` JSONP, `li
580589

581590
**Then look at what it costs on the wire.** `yarn test:size` — and the `Code Size` CI job, which compares against the report `main` last uploaded and comments the diff on the pull request — builds every `configCases/` case and reports **one row per changed asset**: raw before → after, plus what each of gzip/brotli/zstd makes of it. **It is information, never a verdict: it does not fail, and a change that moves the numbers is not a defect.** It exists to answer two questions, so answer them:
582591

583-
- **Which files changed, and by how much?** The asset table is the headline, so a generator or minifier change reads as the files it moved rather than as one number over the suite. A suite-wide total is deliberately not reported: it says nothing you can act on. Raw is what the generator wrote; the compressed columns are what a user downloads, and the two disagree often enough to be worth reading together — a rewrite that saves raw bytes but not gzip bytes has mostly moved entropy around.
592+
- **Which files changed, and by how much?** The asset table is the headline, so a generator or minifier change reads as the files it moved rather than as one number over the suite. A suite-wide total is deliberately not reported: it says nothing you can act on. Raw is what the generator wrote; the compressed columns are what a user downloads, and the two disagree often enough to be worth reading together — a rewrite that saves raw bytes but not gzip bytes has mostly moved entropy around. Which column decides it is [gzip](#verifying-a-performance-or-memory-change).
584593
- **Which way did it go?** A row is marked 🔴 ↑ when it grew and 🟢 ↓ when it shrank, so the direction reads before the number does.
585-
- **What is a change, and what is merely new?** An asset both runs emit has a before and an after, so it is a change; one only this run emits is a whole new file whose size is not a delta of anything. They are reported in separate tables — changed first and unfolded, new and deleted folded away, each with its own row budget — and counted in separate columns (`Raw change` against `Raw new/gone`), because a pull request adding test cases brings whole bundles with it that would otherwise outrank and bury every real change.
594+
- **What is a change, and what is merely new?** An asset both runs emit has a before and an after, so it is a change; one only this run emits is a whole new file whose size is not a delta of anything. They are reported in separate tables — changed first and unfolded, new and deleted folded away, each with its own row budget — and counted in separate columns (`Gzip change` / `Raw change` against `Gzip new/gone` / `Raw new/gone`), because a pull request adding test cases brings whole bundles with it that would otherwise outrank and bury every real change.
586595
- **Did a runtime gain or lose a runtime module?** A second table counts the runtime modules each runtime carries and names the ones that came or went, split the same way — a runtime a new case brought in gained nothing. Bytes are deliberately not reported per runtime module — what one weighs in isolation is not what anyone downloads, and the asset table already carries the real number. The count is: it catches a runtime module added for one target and forgotten for another, which is the mistake this section is about.
587596

588597
Read the "emitted nothing" note before the numbers: a case whose build now errors contributes no bytes, which otherwise reads as an improvement.

‎lib/css/syntax.js‎

Lines changed: 120 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -3174,9 +3174,8 @@ const consumeABlocksContentsInto = (ts, onNode, streamDepth, streamRule) => {
31743174
decls.push(decl);
31753175
if (_nodeCount > limit) {
31763176
if (_streamWriter !== undefined && rules === null) {
3177-
// A block of declarations only is the one the printer may
3178-
// still merge a longhand family in, which needs all of them at
3179-
// once. Wait for a child rule, which is what turns that off.
3177+
// The longhand merge needs every declaration at once; a child
3178+
// rule is where that is given up rather than hold the block.
31803179
limit = _nodeCount + _STREAM_MIN_NODES;
31813180
} else {
31823181
if (!published) {
@@ -7647,6 +7646,8 @@ const _isUnterminatedUrl = (raw) => {
76477646
* keeps its wrapper — the other kind is the cheap one there. Value-identical; a
76487647
* `\`-newline continuation is left alone because dropping it could fuse into a
76497648
* preceding hex escape.
7649+
* A hex escape stays as written: the character it names costs gzip bytes where
7650+
* it saves raw ones (measured in `configCases/css/minimize-values`).
76507651
* @param {string} raw the string token's source text, quotes included
76517652
* @returns {string} the normalized string token
76527653
*/
@@ -8049,30 +8050,10 @@ const _valueComponents = (path, node, writer) => {
80498050
};
80508051

80518052
/**
8052-
* What a comment-only gap in a custom property's value prints as: the kept
8053-
* comments in it where they stood, otherwise the boundary it stands for — a
8054-
* space where the tokens either side would fuse, and nothing where they part.
8055-
* @param {PrintContext} writer the print context (holds the kept comments)
8056-
* @param {number} start first source offset of the gap
8057-
* @param {number} end offset past its last
8058-
* @param {string} out the value printed so far
8059-
* @param {string} next the token about to follow it (empty at the end)
8060-
* @returns {string} the gap's text
8061-
*/
8062-
const _customPropertyGap = (writer, start, end, out, next) => {
8063-
const kept = writer.takeInserts(start, end);
8064-
if (kept !== "") return kept;
8065-
return next !== "" &&
8066-
_wouldFuseTokens(out.charCodeAt(out.length - 1), next, out)
8067-
? " "
8068-
: "";
8069-
};
8070-
8071-
/**
8072-
* A custom property's value as written — the tokens are the value, and the
8073-
* CSSOM hands this text back, so nothing in it is rewritten. A comment is the
8074-
* one exception: it is no tree node, so it survives as a gap between two of
8075-
* them, which {@link _customPropertyGap} prints as the boundary it stood for.
8053+
* A custom property's value, token for token: every token is written back as
8054+
* written, and a run of whitespace and dropped comments between two of them is
8055+
* one boundary — the space they need, or nothing where a comma or a block edge
8056+
* is already one, which leaves every `var()` the same token stream.
80768057
* @param {CssPath} path the accessor positioned on the declaration
80778058
* @param {ComponentValue[]} children the tokens to print
80788059
* @param {PrintContext} writer the print context (holds the kept comments)
@@ -8083,22 +8064,81 @@ const _customPropertyGap = (writer, start, end, out, next) => {
80838064
const _customPropertyValue = (path, children, writer, from, to) => {
80848065
let out = "";
80858066
let at = from;
8067+
// The boundary held back: whether a whitespace token stood in it, whether a
8068+
// dropped comment did, and whether a comma closed it.
8069+
let spaced = false;
8070+
let dropped = false;
8071+
let comma = false;
80868072
for (const child of children) {
8087-
const text = _customPropertyToken(path, child, writer);
80888073
const start = path.start(child);
80898074
// Every other token is a child of its own, so a gap is comments only.
8090-
if (at !== start) out += _customPropertyGap(writer, at, start, out, text);
8091-
out += text;
8075+
if (at !== start) {
8076+
const kept = writer.takeInserts(at, start);
8077+
if (kept === "") {
8078+
dropped = true;
8079+
} else {
8080+
if (spaced && out !== "") out += " ";
8081+
out += kept;
8082+
spaced = false;
8083+
dropped = false;
8084+
comma = false;
8085+
}
8086+
}
80928087
at = path.end(child);
8088+
const type = path.type(child);
8089+
if (type === T_WHITESPACE) {
8090+
spaced = true;
8091+
continue;
8092+
}
8093+
if (type === T_COMMA) {
8094+
out += ",";
8095+
spaced = false;
8096+
dropped = false;
8097+
comma = true;
8098+
continue;
8099+
}
8100+
const text = _customPropertyToken(path, child, writer);
8101+
// A comma or a block delimiter is a boundary of its own, so the whitespace
8102+
// beside one says nothing — except before `(`, which an ident in front of
8103+
// makes a function token, and that is what `_wouldFuseTokens` answers.
8104+
if (!comma && out !== "") {
8105+
const last = out.charCodeAt(out.length - 1);
8106+
const fuses = dropped && _wouldFuseTokens(last, text, out);
8107+
const parted =
8108+
CUSTOM_PROPERTY_CLOSERS.includes(out[out.length - 1]) ||
8109+
CUSTOM_PROPERTY_OPENERS.includes(text[0]);
8110+
if (fuses || (spaced && !parted)) out += " ";
8111+
}
8112+
out += text;
8113+
spaced = false;
8114+
dropped = false;
8115+
comma = false;
8116+
}
8117+
// A trailing boundary separates the last token from a `)` or the value's end,
8118+
// neither of which it can fuse with; only a kept comment in it still prints.
8119+
if (at !== to) {
8120+
const kept = writer.takeInserts(at, to);
8121+
if (kept !== "") {
8122+
if (spaced && out !== "") out += " ";
8123+
out += kept;
8124+
}
80938125
}
8094-
if (at !== to) out += _customPropertyGap(writer, at, to, out, "");
80958126
return out;
80968127
};
80978128

8129+
/** What makes a token worth reading through rather than writing back whole. */
8130+
const CUSTOM_PROPERTY_REWRITABLE_RE = /[\t\n\f\r ,]|\/\*/;
8131+
8132+
// Block delimiters a token cannot fuse across, so whitespace beside one goes.
8133+
// `(` is not among the openers: an ident in front of it makes a function token.
8134+
const CUSTOM_PROPERTY_CLOSERS = ")]}";
8135+
const CUSTOM_PROPERTY_OPENERS = "[{";
8136+
80988137
/**
80998138
* One token of a custom property's value, as written — recursing into a
8100-
* function or block so a comment nested in one minifies too. A source holding
8101-
* no `/*` holds no comment at any depth, so it is written back whole.
8139+
* function or block so the boundaries nested in one print as they do at the top
8140+
* level. A source holding neither whitespace, a comma nor a comment holds none
8141+
* at any depth, so it is written back whole.
81028142
* @param {CssPath} path the accessor positioned on the declaration
81038143
* @param {ComponentValue} child the token to print
81048144
* @param {PrintContext} writer the print context (holds the kept comments)
@@ -8108,8 +8148,8 @@ const _customPropertyToken = (path, child, writer) => {
81088148
const source = path.source(child);
81098149
const type = path.type(child);
81108150
if (
8111-
!source.includes("/*") ||
8112-
(type !== T_FUNCTION && type !== T_SIMPLE_BLOCK)
8151+
(type !== T_FUNCTION && type !== T_SIMPLE_BLOCK) ||
8152+
!CUSTOM_PROPERTY_REWRITABLE_RE.test(source)
81138153
) {
81148154
return source;
81158155
}
@@ -8376,7 +8416,9 @@ const _dropShadowZeroLengths = (property, components) => {
83768416
let start = end;
83778417
while (start > 0 && _NUMERIC_RE.test(layer[start - 1])) start--;
83788418
let last = end;
8379-
while (last - start > minimum && layer[last - 1] === "0") {
8419+
// The components are as authored — the zero-unit drop prints later — so a
8420+
// trailing zero is `0px` as often as `0`.
8421+
while (last - start > minimum && _isZeroLength(layer[last - 1])) {
83808422
last--;
83818423
changed = true;
83828424
}
@@ -9234,9 +9276,20 @@ const _familyValue = (longhands, values) => {
92349276
* a `/` stands between
92359277
* @param {Map<string, number>} at which declaration wrote each property, by name
92369278
* @param {Set<string>} repeated the properties written more than once
9279+
* @param {Uint32Array | null} rulesBefore how many child rules stand before each
9280+
* declaration, or null where the block holds none
92379281
* @returns {Map<Node, string> | null} replacement text per declaration, or null
92389282
*/
9239-
const _mergeBoxLonghands = (path, decls, writer, table, mode, at, repeated) => {
9283+
const _mergeBoxLonghands = (
9284+
path,
9285+
decls,
9286+
writer,
9287+
table,
9288+
mode,
9289+
at,
9290+
repeated,
9291+
rulesBefore
9292+
) => {
92409293
/** @type {Map<Node, string> | null} */
92419294
let out = null;
92429295
// What an earlier shorthand of this table already wrote or blanked. Two of
@@ -9259,6 +9312,13 @@ const _mergeBoxLonghands = (path, decls, writer, table, mode, at, repeated) => {
92599312
const indexes = longhands.map((l) => /** @type {number} */ (at.get(l)));
92609313
if (indexes.some((i) => claimed.has(decls[i]))) continue;
92619314
const ordered = [...indexes].sort((a, b) => a - b);
9315+
// A child rule between the first and the last is one the merge steps over.
9316+
if (
9317+
rulesBefore !== null &&
9318+
rulesBefore[ordered[ordered.length - 1]] !== rulesBefore[ordered[0]]
9319+
) {
9320+
continue;
9321+
}
92629322
// The merge moves whatever stands between the four below the shorthand, so
92639323
// nothing between them may write one of those properties. Blocked by name
92649324
// prefix rather than by a writers table: `mdn-data` maps `margin-top` back
@@ -10489,11 +10549,8 @@ const printer = (path, writer) => {
1048910549
? name
1049010550
: _standardSpelling(toLowerCaseIfNeeded(name));
1049110551
if (custom) {
10492-
// A custom property's value is the text `getPropertyValue()` hands
10493-
// back, so rewriting it builds a different CSSOM from the same
10494-
// document — which `syntaxEquivalence` forbids, whatever a
10495-
// substitution would read. As written, then; only the comments in it
10496-
// minify, down to the boundary they stand for.
10552+
// `getPropertyValue()` hands this text back, so a rewritten token
10553+
// would be a different CSSOM; only the boundaries between them go.
1049710554
const from = path.start(path.childAt(path.node, 0));
1049810555
const to = path.end(path.childAt(path.node, count - 1));
1049910556
if (minify) {
@@ -10592,10 +10649,9 @@ const printer = (path, writer) => {
1059210649
}
1059310650
// A family's longhands are their shorthand, so they print as it — four
1059410651
// sides or corners, the two a pair shorthand sets, or the slots of an
10595-
// order-free one. Only with a child rule out of the way: one between them
10596-
// would be stepped over by the merge, which the adjacency check cannot
10597-
// see. Earlier tables win, though no property is in two of them.
10598-
const mergeable = minify && (rules === null || rules.length === 0);
10652+
// order-free one. Earlier tables win, though no property is in two of
10653+
// them.
10654+
const mergeable = minify;
1059910655
/** @type {Map<Node, string>[]} */
1060010656
const merges = [];
1060110657
if (mergeable && decls.length >= 2) {
@@ -10616,6 +10672,22 @@ const printer = (path, writer) => {
1061610672
at.set(property, i);
1061710673
}
1061810674
if (mergeableNames >= 2) {
10675+
// Child rules before each declaration: a family whose first and last
10676+
// count the same has none between them for the merge to step over.
10677+
/** @type {Uint32Array | null} */
10678+
let rulesBefore = null;
10679+
if (items !== decls) {
10680+
rulesBefore = new Uint32Array(decls.length);
10681+
let seen = 0;
10682+
let next = 0;
10683+
for (let i = 0; i < items.length; i++) {
10684+
if (next < decls.length && items[i] === decls[next]) {
10685+
rulesBefore[next++] = seen;
10686+
} else {
10687+
seen++;
10688+
}
10689+
}
10690+
}
1061910691
for (const [table, mode] of MERGE_TABLES) {
1062010692
const merged = _mergeBoxLonghands(
1062110693
path,
@@ -10624,7 +10696,8 @@ const printer = (path, writer) => {
1062410696
table,
1062510697
mode,
1062610698
at,
10627-
repeated
10699+
repeated,
10700+
rulesBefore
1062810701
);
1062910702
if (merged !== null) merges.push(merged);
1063010703
}

0 commit comments

Comments
 (0)