Skip to content

Commit 0cde758

Browse files
feat(css,html): fold every case-insensitive CSS name, and name each minifier rewrite as an option (#21834)
* feat(css): print every case-insensitive name in one case CSS matches a property, at-keyword, function, `url()`, pseudo, media feature, media type and unit ASCII case-insensitively, but the printer wrote each back as authored — so one document could spell the same name several ways and a compressor saw each as its own token. Each is now printed lowercase, and the names whose canonical spelling carries a capital keep it: `translateX` and the ten other transforms `mdn-data`'s function table capitalizes, and `Hz` / `kHz` / `Q` from its unit table, derived in the generator rather than listed. What stays as authored: a type selector (`linearGradient` is its own SVG element), an id, a class, an attribute name and its value, a custom property, a `@keyframes` / `@container` / custom-media name, a name carrying an escape (`\G` is not `\g`), and `@charset`, which the engine reads as literal bytes rather than matching. * feat(css): lowercase a keyword value where the property takes no name 271 properties spell their whole value out as keywords — `display`, `position`, `float`, `overflow`, every `*-style`, `white-space` — and CSS matches each ASCII case-insensitively, so an identifier standing directly in one of their values is a keyword rather than a name of the author's and can be printed the one way it matches. The set is derived in the generator from the same grammar walk the other property tables use: a property qualifies when its top-level value grammar reaches no value class at all. A call's arguments are read against the function's grammar, not the property's, so the printer lowercases only an identifier that is a direct child of the declaration — which is also what keeps `stylistic(Foo)` and `var(--Foo)` untouched. The property lookup runs only once the identifier is known to carry a capital, so a value already written lowercase costs one scan it was paying for anyway. * feat(css): name each minifier rewrite on optimization.minimize.css Every CSS rewrite was unconditional, so a document one of them tripped over could only be minified by turning minification off altogether. Ten switches now name them — `colors`, `escapes`, `functions`, `lowercase`, `mediaQueries`, `numbers`, `quotes`, `rules`, `selectors`, `shorthands` — each on unless it is `false`, and each read off the same `optimization.minimize.css` object `convertLengthUnits` already sits in. The HTML minimizer hands them to the CSS minifier it runs over an inline `<style>` and every `style=""`, so an inline declaration is rewritten by the same switches its `.css` twin is. Inside the printer they are one fixed-shape object rather than a flag apiece, read once per print and asked at the head of the helper each rewrite already lived in, so a switch left alone costs one property read on the path that was going to run anyway. A keyword value on a property that takes a color is lowercased with the rest now: `<color>` is keywords and numbers, so `CanvasText` there is the `canvastext` the CSSOM hands back. * feat(html): name each minifier rewrite on optimization.minimize.html The HTML side had the same gap the CSS side did: a page one rewrite tripped over could only be minified by turning minification off. Ten switches now name them — `booleanAttributes`, `comments`, `enumeratedAttributes`, `listAttributes`, `minifyJson`, `minifyStyles`, `numericAttributes`, `optionalTags`, `quotes`, `urlAttributes` — each on unless it is `false`, which is what the value-rewrite TODO asked for. `optionalTags` covers the tags §13.1.2.4 lets the parser imply other than the `<html>` / `<head>` / `<body>` shell; `removeImpliedTags` keeps that shell to itself, so the two do not overlap. The CSS switches the HTML minimizer forwards to the nested CSS minifier are now `cssTransforms`, leaving `transforms` for HTML's own — each language picks its own out of the flat options object with its own `pickTransforms`. * perf(css): stop restating what the minifier's data tables can derive Three things the generated tables said twice, and one that cost a thousand objects to say at all: - `PREFIX_BROWSERS` was `SUPPORT_BROWSERS` name for name. There is one list of browsers the tables answer for, so a browser is now named by its place in it — which is also the slot a parsed selection holds its versions in, so no lookup goes through a name any more. - `PREFIX_WINDOWS` held 710 three-element arrays inside 154 lists, each repeating one of thirteen browser names; `SUPPORT_PROFILES` held 73 rows of thirteen. Both are now one `Float64Array` of numbers laid end to end, the windows indexed by a `PREFIX_WINDOW_STARTS` companion. - `Infinity` marked a version that never arrives, which prints as an identifier and cost the emitted file six times its lines; a finite `NEVER` past every real version does the same job as a number. - `SVG_TAG_ADJUST` and `SVG_ATTR_ADJUST` keyed 95 camelCase names by the same names lowercased. The generator states the names alone now and the key is derived, so a key cannot drift from its value. `lib/css/data.js` retains 747 KiB where it retained 863 KiB, measured with `--expose-gc` over six collections; the file itself is 152 KiB where it was 159 KiB, and `lib/html/data.js` 46 KiB where it was 47 KiB. * refactor(css): say each of the printers' repeated blocks once Five blocks the CSS and HTML printers stated twice, each now one definition — same code, same call profile, none of it on a per-token path: - resolving and picking the per-transform switches was verbatim in both languages, so it moves to `util/SourceProcessor`, which is where the rest of what the two share already lives; - `_releaseColumns` gives the node columns back, so a new column is added in one place rather than in two that have to agree; - `_enterAtRulePrelude` sets the flags an at-rule's name decides, which the collected and streaming walks were spelling out separately; - `_emitHeld` emits the top-level rule held back for a join, from the four sites that each wrote its seven arguments out; - `_fosterPlace` is §13.2.6.1's foster-parenting place, which the adoption agency's copy carried a "reuse appropriatePlace logic but rooted differently: emulate" note over. Minifying `test/configCases/css/large/tailwind.module.css` takes the same time either side — medians 233.8/228.5 ms before, 234.8/224.3 ms after, against a 15 ms run-to-run spread — for byte-identical output, and the 20330 html5lib tree-construction cases still pass. * test: refresh the CLI flags the minifier switches add Every schema property becomes a CLI flag, so the twenty switches `optimization.minimize.css` and `.html` now name add twenty entries to the snapshot the flags are read back from. * feat(css): name the minimizer's comment handling, and part it from HTML's Dropping comments was the one CSS rewrite no option reached: csso and cssnano both name it, and turning it off meant turning minification off. `optimization.minimize.css.comments` now names the three levels csso does — `true` keeps a `/*!` banner, an `@license` / `@preserve` annotation and the source-map pragma, `false` keeps every comment, and `"all"` keeps nothing but the pragma — with `preserveComments` patterns outranking all three, as the HTML minimizer's already do. Two things this turned up: - both languages name a `quotes` and a `preserveComments`, and the HTML minimizer was handed one flat object holding both sets, so `minimize.css.quotes` decided HTML's attribute quoting and `minimize.html.preserveComments` decided what an inline `<style>` kept. `optimization.minimize.css` now rides under its own key, and each language picks its switches out of its own object; - a quoted `url()` decoded its data-URI percent-escapes only when `quotes` was on, though `escapes` is what documents that rewrite. The two now answer for one thing each, so a data URI can shed its escapes and keep its quotes. Probing every transform `cssnano-preset-default` runs against the switch set: each one webpack implements is now reachable by exactly one switch, save collapsing whitespace, which is what minifying is. * fix(css): let the transform switches and renderEmbeddedSource compose Rebasing the switches onto #21830 put three of its lines inside a `url()` that now asks two switches about its own spelling, and text that merges cleanly is not the same as meaning that does: - the renderer reads a data URL's payload, which is what the percent-escapes hold, so it is offered the decoded one whatever `escapes` says — that switch decides how the escapes are printed, not whether a data URL holds a document; - what the renderer hands back is no longer what the quotes were written around, so `_serializeUrl` picks its spelling afresh — and the two spellings below the quoted one are the unquoting `quotes` names, so with it off the payload keeps its quotes; - a rendered bare `url()` writes the lowercased `url(` the rest of them do. * feat(css,html): one comments option per language, in terser's six forms `comments` and `preserveComments` were two options answering one question, and neither answered it the way the JavaScript side already does. They fold into `comments`, which takes what terser's `format.comments` takes: `"some"` (the default) keeps the ones that carry something, `true` / `"all"` keeps every comment, `false` keeps none, and a string, a `RegExp` or a `(comment) => boolean` is asked about each comment's own text — standing in for the default rule rather than beside it, as terser's does, so a pattern that names nothing else drops what `"some"` would have kept. Each language keeps a floor no level reaches past, because the two mean different things by "a comment that carries something": CSS keeps the `/*#` source-map pragma, which is a link; HTML keeps a downlevel conditional comment, a server-side include and a `<?…?>` directive, which are code. A predicate reaches the minimizer's worker pool through the same serialize-and-evaluate path terser's does, so it works under parallel minification and must not close over anything. The seven changesets this branch had collapse into the one entry the whole of it is. * feat(css,html): name each minifier switch for what it does to what `functions` said what a switch was about and nothing about what it did with it, and it was not alone: `colors`, `escapes`, `numbers`, `quotes`, `rules`, `selectors`, `shorthands` and HTML's `booleanAttributes`, `optionalTags`, `quotes`, `urlAttributes` and the three `*Attributes` read the same way. Every one is now verb-first, which is what `cssnano-preset-default` (`discardComments`, `mergeRules`, `minifySelectors`, `reduceTransforms`), html-minifier-terser (`collapseBooleanAttributes`, `removeOptionalTags`, `removeAttributeQuotes`) and webpack's own older HTML options (`collapseWhitespace`, `removeEmptyAttributes`) already do: colors -> shortenColors booleanAttributes -> collapseBooleanAttributes escapes -> shortenEscapes optionalTags -> removeOptionalTags functions -> reduceFunctions quotes -> normalizeAttributeQuotes lowercase -> lowercaseNames urlAttributes -> trimUrlAttributes mediaQueries -> shortenMediaQueries enumeratedAttributes -> normalizeEnumeratedAttributes numbers -> shortenNumbers listAttributes -> normalizeListAttributes quotes -> normalizeQuotes numericAttributes -> normalizeNumericAttributes selectors -> shortenSelectors Two CSS switches did two things each, which no single verb could say honestly, so each splits the way cssnano splits it: `rules` into `removeDeadRules` and `mergeRules`, `shorthands` into `shortenValues` and `mergeLonghands`. Probing every transform against the new names turned up one gate that was missing rather than misnamed: writing an empty attribute value as the bare name is the `=""` going, which is a quoting decision, so it answers to `normalizeAttributeQuotes` like the rest of them. * perf(css): stop folding a name twice, and read the tables once Proving the re-encoded version tables cost nothing turned up what does. Measured against a null test — the same build under both names, which this machine calls ±0.6% — the branch was 5-9% slower than main on real stylesheets, and every bit of it was the case folding walking a name a second time: - a value identifier was folded by `toLowerCaseIfNeeded` for the named colour lookup and again by `asciiLowerCaseName` for the keyword one. One fold now answers both, and the second walk is the shouted names' to pay; - a declaration's name was folded for the value rules and again to be printed. Same fix; - `asciiLowerCaseName` walked the characters to ask whether anything folds at all. `toLowerCase` answers that natively and hands back the very string it was given where nothing does, so it is a pointer compare and no allocation; - the canonical-spelling table was read for every number and every call, where only a name that carried a capital can have an entry; - a `url()` cut its own name out to fold it, on every url; - `_inKeywordOnlyValue` read, folded and looked up the property once per identifier rather than once per declaration. And one that was neither: `_transforms` was the frozen table where no switch was set and a copy where one was, and `Object.freeze` gives an object a hidden class of its own — so every one of the ~45 reads, one per token, saw two shapes. It is always a copy now, made the one way. What is left, against the same null test: the branch is +1.3% on tailwind and +0.5% on bootstrap with the folding off — where its output is byte-identical to main's — and +2.3% to +6.6% with it on, which is the feature, and `lowercaseNames: false` is the switch that returns it. The re-encoded tables are themselves 1.4% *faster* on tailwind, and `lib/css/data.js` retains 753 KiB where main's retains 842. * refactor(css,html): drop the three switches nothing needs to turn off `lowercaseNames`, `shortenEscapes` and `trimUrlAttributes` named rewrites the spec makes safe by construction, and none of the three is a place a bug could hide that the others do not already cover: - an escape and the character it names are one token (CSS Syntax 3 §4.3.7), so shortening one cannot change what parses. Both escape rewrites predate this branch and had no switch before it; - so does trimming a URL attribute: the URL parser strips the leading and trailing whitespace before it resolves anything (URL §4.4); - and every name CSS matches ASCII case-insensitively means the same thing in either case, which is the whole premise of the folding. They join the normalizations that were already unconditional for the same reason — collapsing whitespace, the `<!doctype>` keyword, HTML tag and attribute names, character references. The one thing a switch was still buying on `lowercaseNames` was a way to decline its cost, so that is gone first: the unit is folded once for both the printed spelling and the angle test rather than twice, and folding a selector's pseudo names now shares the pass that drops a CSS2 pseudo-element's second colon — the two read the same part after the same `:`, and the fold is what the legacy name is then matched against. Against a null test of ±1.1%, the branch is +2.0% on bootstrap, +2.1% on bulma and +2.3% on tailwind, where it was +2.3% to +6.6% before. * refactor(css,html): keep each printer's options in its own file `util/SourceProcessor.js` is the visitor coordinator every language binds its own grammar to, and it had no business knowing what a minifier switch or a comment is. It grew three helpers because the two syntaxes held identical copies and a de-duplication pass moved them to the nearest shared file — which optimized for repeating no lines over each module owning its own concern, and put language detail in the one file that is meant to stay language-agnostic and is the one most likely to be standardized or made public. The file is byte-identical to `main` again. Each syntax now resolves its own `transforms`, picks its own switches out of a wider options object and reads its own `comments` level, over its own table — and the two are free to part, which is already true: CSS's `"some"` keeps a `/*!` banner and HTML's keeps a server-side directive. The two copies are near-identical today and that is the point: the duplication is between two files that describe different languages, where the shared helper was a coupling between them. What had to survive the move is the hidden-class discipline — a resolved object is built by spreading the frozen table and writing over names it already has, so every per-token read of `_transforms` sees one shape. Both copies do, and it measures the same: byte-identical output either side of the move, and against a null test of ±0.2% the branch is -0.0% on bootstrap and +2.5% on tailwind, where it stood before it. * fix(css,html): keep a name folded only where the engine reads it back The case fold reached two places it must not. A value the engine keeps as the tokens it was written as until a substitution resolves now prints its function, url and unit spellings as written, and an `@font-feature-values` sub-rule's declaration names stay case-sensitive: they are `<custom-ident>` feature values, so folding made two distinct entries collide. Also from review: `optimization.minimize.css: false` now reaches the CSS inside a document, `reduceFunctions` and `mergeLonghands` govern the last rewrite each was missing, a comment selector decides the source-map pragma like any other comment, and a parser-inserted table group prints its start tag whenever its end tag prints. * fix(config): leave minimize.css to the css assets, and refresh the cli snapshot `minimize.css: false` selects which asset types are minimized, not whether CSS is rewritten anywhere: `configCases/optimization/minimize-html-only` states that a disabled type carries no options to forward, and its inline css still minifies. `minimize.html.minifyStyles: false` is the switch for that, which this branch is what adds. The cli flags are derived from the schema, so the `comments` description moves `Cli.basictest`'s snapshot with it. * test(html): drive the second table group's kept start tag
1 parent 0b5c4e9 commit 0cde758

53 files changed

Lines changed: 3656 additions & 2534 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
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+
Print CSS names in one case, and name each CSS/HTML minifier rewrite an option.

‎cspell.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"callees",
5151
"callme",
5252
"camelcase",
53+
"canvastext",
5354
"carryforward",
5455
"chainable",
5556
"checkmark",
@@ -379,6 +380,9 @@
379380
"rvalue",
380381
"samsunginternet",
381382
"sandboxed",
383+
"scalex",
384+
"scaley",
385+
"scalez",
382386
"SAPUI",
383387
"sccs",
384388
"selectedcontent",
@@ -414,6 +418,7 @@
414418
"Stensberg",
415419
"stringable",
416420
"strtok",
421+
"styleset",
417422
"stylesheet",
418423
"subdir",
419424
"subfolder",
@@ -427,6 +432,7 @@
427432
"syncloader",
428433
"systemjs",
429434
"tabatkins",
435+
"tabindex",
430436
"tapable",
431437
"Tarjan",
432438
"tebibytes",

‎declarations/WebpackOptions.d.ts‎

Lines changed: 109 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2405,36 +2405,111 @@ export interface OptimizationMinimizeOptions {
24052405
javascript?: false | OptimizationMinimizeJavascript;
24062406
}
24072407
/**
2408-
* What the CSS minimizer may do beyond the transforms that always apply. Applies wherever it runs: on `.css` assets and on the inline `<style>` / `style=""` the HTML minimizer hands it.
2408+
* What the CSS minimizer does. Applies wherever it runs: on `.css` assets and on the inline `<style>` / `style=""` the HTML minimizer hands it. Every transform that keeps the stylesheet's meaning is on by default and may be turned off on its own, so a document a rewrite breaks can be minimized without it while the rest still applies; the two that change what the CSSOM hands back (`convertLengthUnits`, `rewriteCustomProperties`) are off until asked for.
24092409
* @since 5.110.0
24102410
*/
24112411
export interface OptimizationMinimizeCss {
2412+
/**
2413+
* Which comments survive. `"some"`, the default, keeps a `/*!` banner and a comment annotated `@license` or `@preserve`; `true` (or `"all"`) keeps every comment and `false` keeps none; a string is read as a regular expression source, and it, a `RegExp` or a `(comment) => boolean` predicate is asked about each comment's own text and keeps the ones it accepts — standing in for the default rule rather than beside it, as terser's `format.comments` does, so a pattern that names nothing else drops the ones `"some"` would have kept. A `/*#` source-map pragma is a link rather than a comment, so `"some"` and `"all"` keep it; `false`, a pattern or a predicate decides it like any other. A predicate is handed to the minimizer's worker pool as source, so it must not close over anything.
2414+
* @since 5.110.0
2415+
*/
2416+
comments?:
2417+
| ("all" | "some")
2418+
| RegExp
2419+
| boolean
2420+
| string
2421+
| ((comment: string) => boolean);
24122422
/**
24132423
* Rewrite a length into a shorter unit it is exactly equal in (`16px` -> `1pc`). Off by default: the authored unit is lost, and once the asset is compressed the rewrite rarely earns anything.
24142424
* @since 5.110.0
24152425
*/
24162426
convertLengthUnits?: boolean;
2427+
/**
2428+
* Write a family of longhands as the one shorthand that sets them — four sides or corners, the two a pair shorthand sets, or the slots of an order-free one — even where unrelated declarations stand between them. On by default.
2429+
* @since 5.110.0
2430+
*/
2431+
mergeLonghands?: boolean;
2432+
/**
2433+
* Join rules nothing stands between: adjacent rules that print the same block become one selector list, at-rules that share a prelude become one rule, and a named `@layer` block a later sibling opens again is folded into the first. On by default.
2434+
* @since 5.110.0
2435+
*/
2436+
mergeRules?: boolean;
2437+
/**
2438+
* Normalize quoting: a string takes whichever quote needs fewer escapes, a `url()` and an attribute selector's value drop theirs where the content is still one token, and a font family whose name is a run of identifiers is written unquoted. On by default.
2439+
* @since 5.110.0
2440+
*/
2441+
normalizeQuotes?: boolean;
2442+
/**
2443+
* Compute a call into the shorter call naming the same value: `calc()` and every math function over constants, a transform naming one axis or an identity, a gradient's default direction and its implied stops, an easing function that has a keyword, and a filter function given the amount an omitted argument already means. On by default.
2444+
* @since 5.110.0
2445+
*/
2446+
reduceFunctions?: boolean;
2447+
/**
2448+
* Drop a rule or declaration nothing can read: a rule whose block ends up empty, a declaration an identical later one in the same block makes dead, and a rule an identical later sibling makes dead. On by default. Joining rules that are not dead is `mergeRules`.
2449+
* @since 5.110.0
2450+
*/
2451+
removeDeadRules?: boolean;
24172452
/**
24182453
* Shorten the values of custom properties (`--x: #ffffff` -> `#fff`, `--y: 0.5rem` -> `.5rem`), which are otherwise written back exactly as authored. Off by default: `getComputedStyle().getPropertyValue()` hands this text back, so a rewritten value is a different CSSOM — the one place a declaration's authored text survives. What it may rewrite is exactly what any other value's tokens may be, a color in a substitution's fallback included — that fallback being the property's value rather than the function's own argument.
24192454
* @since 5.110.0
24202455
*/
24212456
rewriteCustomProperties?: boolean;
2457+
/**
2458+
* Write each color in the shortest spelling of the same value: `#ffffff` -> `#fff`, `rgb(1 2 3)` -> `#010203`, a named color where the property takes no identifier of the author's own, and every polar and Lab function the target agrees with hex on. On by default.
2459+
* @since 5.110.0
2460+
*/
2461+
shortenColors?: boolean;
2462+
/**
2463+
* Write a media feature in its range spelling where the target reads one (`(min-width:100px)` -> `(width>=100px)`), and collapse an `and` of two one-sided ranges into the interval it describes. On by default.
2464+
* @since 5.110.0
2465+
*/
2466+
shortenMediaQueries?: boolean;
2467+
/**
2468+
* Write each number in its shortest equal spelling — dropping a leading zero, a trailing fraction and a `+`, rounding to the six significant digits a stylesheet can observe, dropping the unit a zero does not need, and writing an alpha and a ratio the one way its grammar spells them. On by default.
2469+
* @since 5.110.0
2470+
*/
2471+
shortenNumbers?: boolean;
2472+
/**
2473+
* Rewrite a selector into an equal one: a selector list deduplicated and ordered, a CSS2 pseudo-element's second colon dropped, the universal a compound already implies dropped, an `An+B` written the shortest way its microsyntax allows, and a `from` / `100%` keyframe selector written as the shorter of the pair. On by default.
2474+
* @since 5.110.0
2475+
*/
2476+
shortenSelectors?: boolean;
2477+
/**
2478+
* Write a value the shortest way its property's own grammar allows: a `{1,4}` box or corner notation collapsed, a slot holding its own initial dropped, and `flex` / `font-weight` / `display` / `transition` / `<position>` / `<repeat-style>` written the short way. On by default. Merging separate longhand declarations is `mergeLonghands`.
2479+
* @since 5.110.0
2480+
*/
2481+
shortenValues?: boolean;
24222482
/**
24232483
* Maintain vendor prefixes for the `browserslist` target: add the `-webkit-` / `-moz-` / `-ms-` spelling of a property, at-rule or pseudo-selector that a selected browser still needs, and drop one none of them does. On by default, and only in effect for a `browserslist` target — any other target names no browsers to prefix for. A browserslist name no compat dataset covers (`op_mini`, `and_uc`, `and_qq`, `baidu`, `kaios`, `bb`) is skipped, and a selection of nothing but those prefixes for no one.
24242484
* @since 5.110.0
24252485
*/
24262486
vendorPrefixes?: boolean;
24272487
}
24282488
/**
2429-
* What the HTML minimizer may do beyond the transforms that always apply.
2489+
* What the HTML minimizer does. Every transform that keeps the document's DOM is on by default and may be turned off on its own, so a page a rewrite breaks can be minimized without it while the rest still applies; the ones that change what a script or a selector reads back are off until asked for.
24302490
* @since 5.110.0
24312491
*/
24322492
export interface OptimizationMinimizeHtml {
2493+
/**
2494+
* Write a boolean attribute spelled with its own name (`disabled="disabled"`) as the bare name the spec canonicalizes it to. On by default.
2495+
* @since 5.110.0
2496+
*/
2497+
collapseBooleanAttributes?: boolean;
24332498
/**
24342499
* Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim. `true` (or `"conservative"`) never removes whitespace entirely — dropping it would join two inline elements that render apart. `"smart"` also drops the whitespace that sits against a block element's edge, where no line box reaches it. `"all"` drops the whitespace at every text node's edges, which does change how adjacent inline elements render.
24352500
* @since 5.110.0
24362501
*/
24372502
collapseWhitespace?: ("conservative" | "smart" | "all") | boolean;
2503+
/**
2504+
* Which comments survive. `"some"`, the default, keeps nothing: every comment an HTML parser reads is inert; `true` (or `"all"`) keeps every comment and `false` keeps none; a string is read as a regular expression source, and it, a `RegExp` or a `(comment) => boolean` predicate is asked about each comment's own text and keeps the ones it accepts — standing in for the default rule rather than beside it, as terser's `format.comments` does, so a pattern that names nothing else drops the ones `"some"` would have kept. A downlevel conditional comment, a server-side include and a `<?…?>` template directive are code rather than comments and stay whatever this says. A predicate is handed to the minimizer's worker pool as source, so it must not close over anything.
2505+
* @since 5.110.0
2506+
*/
2507+
comments?:
2508+
| ("all" | "some")
2509+
| RegExp
2510+
| boolean
2511+
| string
2512+
| ((comment: string) => boolean);
24382513
/**
24392514
* Print a run of adjacent `<style>` elements as one sheet. Off by default: it removes elements, so `document.styleSheets`, a `style:nth-child()` selector and `querySelectorAll("style").length` all read a different document. A sheet the CSS minifier does not accept is never folded — appending to one that may be unterminated would make the next sheet part of its last rule — and neither is one led by `@import` / `@charset` / `@namespace`, which apply only at the top of a sheet.
24402515
* @since 5.110.0
@@ -2445,16 +2520,41 @@ export interface OptimizationMinimizeHtml {
24452520
* @since 5.110.0
24462521
*/
24472522
minifyConditionalComments?: boolean;
2523+
/**
2524+
* Strip the whitespace between the tokens of a `<script>` whose type is a JSON MIME type. Every literal is copied byte for byte, so no number is rounded and no escape rewritten. On by default.
2525+
* @since 5.110.0
2526+
*/
2527+
minifyJson?: boolean;
24482528
/**
24492529
* Minify the document held in an `<iframe srcdoc>` attribute. Off by default: the body is a whole document of its own (its base URL is `about:srcdoc`), so minifying it is safe, but the attribute is readable from script and a consumer comparing `iframe.srcdoc` byte for byte would see it change.
24502530
* @since 5.110.0
24512531
*/
24522532
minifySrcdoc?: boolean;
24532533
/**
2454-
* Patterns naming comments to keep, on top of the ones minifying always keeps (downlevel conditional comments, server-side includes and template directives). A string is read as a regular expression source and matched against the comment's text.
2534+
* Run the CSS minimizer over an inline `<style>` element and every `style=""` attribute, with the options `optimization.minimize.css` names. On by default.
24552535
* @since 5.110.0
24562536
*/
2457-
preserveComments?: (RegExp | string)[];
2537+
minifyStyles?: boolean;
2538+
/**
2539+
* Write an attribute value with whichever delimiters cost least — bare where the grammar allows it, else under the quote that needs fewer character references. On by default: the DOM reads the same value either way.
2540+
* @since 5.110.0
2541+
*/
2542+
normalizeAttributeQuotes?: boolean;
2543+
/**
2544+
* Fold an enumerated attribute's value to the keyword it names (`type="TEXT"` -> `type=text`), which the DOM matches ASCII case-insensitively. A value the spec does not enumerate is left as written. On by default.
2545+
* @since 5.110.0
2546+
*/
2547+
normalizeEnumeratedAttributes?: boolean;
2548+
/**
2549+
* Normalize a list-shaped attribute value: a space-separated token list (`class`, `rel`, `part`, …), a comma-separated one (`accept`, `sizes`, …), a `srcset` and the viewport `<meta content>`. On by default. Reordering a token list is `sortTokenLists`, which is separate and off by default.
2550+
* @since 5.110.0
2551+
*/
2552+
normalizeListAttributes?: boolean;
2553+
/**
2554+
* Write an integer attribute (`tabindex`, `colspan`, `width`, …) the one way its own rules read it — leading whitespace, a `+` and leading zeros all go. On by default.
2555+
* @since 5.110.0
2556+
*/
2557+
normalizeNumericAttributes?: boolean;
24582558
/**
24592559
* Drop an attribute whose empty or all-whitespace value leaves it in the state its absence gives: the globals `class`, `id`, `style`, `dir`, `accesskey`, `itemprop`, `itemref`, `itemtype` and `part`, and every attribute reflecting a token list on the elements the spec defines it for — `rel` on `<a>`, `<area>`, `<form>` and `<link>`, `ping` on `<a>` and `<area>`, `headers` on `<td>` and `<th>`, `blocking` on `<link>`, `<script>` and `<style>`, `sizes` on `<link>`, `for` on `<output>` — where an empty list is no tokens. Anywhere else that spelling is an author attribute whose meaning is a script's, so `<x-foo rel="">` and `<label for="">` keep it. Off by default: an attribute selector matches on presence, so `[class]` stops matching. Never dropped: `title` and `lang`, whose empty value means what absence does not; `sandbox`, whose empty list is the most restrictive state an `<iframe>` has; and an event handler, whose empty body still compiles to a function where absence reads null.
24602560
* @since 5.110.0
@@ -2470,6 +2570,11 @@ export interface OptimizationMinimizeHtml {
24702570
* @since 5.110.0
24712571
*/
24722572
removeImpliedTags?: ("smart" | "all") | boolean;
2573+
/**
2574+
* Leave out a tag §13.1.2.4 lets the parser imply, other than the `<html>` / `<head>` / `<body>` shell, which `removeImpliedTags` decides on its own. On by default: nothing can observe the difference, the tree parses the same either way. A tag still stays wherever the spec keeps it — a comment or whitespace behind it, or a following element the insertion mode does not close it through.
2575+
* @since 5.110.0
2576+
*/
2577+
removeOptionalTags?: boolean;
24732578
/**
24742579
* Drop an attribute whose value is the one the element already defaults to. Off by default: an attribute a page no longer carries is one `getAttribute` and every attribute selector read differently, whichever tier dropped it. `true` (or `"smart"`) drops only markers on elements that render nothing — `<script type=text/javascript>`, `<script language=javascript>`, `<script charset=utf-8>`, `<style type=text/css>`, `<link type=text/css>`, `<link media=all>` — so no rule that styles the page stops applying, which is what `@swc/html` does by default. `"all"` also drops spec defaults such as `<input type=text>` and `<form method=get>`, which reaches further still: an attribute selector matches the content attribute, not the reflected default, so `input[type=text]` stops matching.
24752580
* @since 5.110.0

‎lib/config/defaults.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2561,9 +2561,13 @@ const applyOptimizationDefaults = (
25612561
}
25622562
if (minifyHtml) {
25632563
minify.push(require("../html/htmlMinify"));
2564+
// `minimize.css` rides along under its own key rather than spread
2565+
// beside the HTML options: the two name some of the same switches
2566+
// (`quotes`, `comments`), and one flat object would hand
2567+
// each language the other's answer.
25642568
minimizerOptions.push({
25652569
environment: cssEnvironment,
2566-
...cssOptions,
2570+
css: cssOptions,
25672571
...htmlOptions
25682572
});
25692573
extensions.push("html");

‎lib/css/cssMinify.js‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
"use strict";
77

8-
/** @import { CssEnvironment } from "./syntax" */
8+
/** @import { CssEnvironment, CssTransformOptions } from "./syntax" */
99
/** @import { SourceMap } from "../util/SourceProcessor" */
1010

1111
/**
@@ -22,7 +22,7 @@
2222
* re-resolves in the worker — via the installed package, or the dev self-link.
2323
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
2424
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
25-
* @param {{ environment?: CssEnvironment, convertLengthUnits?: boolean, rewriteCustomProperties?: boolean }=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`)
25+
* @param {{ environment?: CssEnvironment, convertLengthUnits?: boolean, rewriteCustomProperties?: boolean } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches)
2626
* @returns {{ code: string, map: SourceMap }} the minified CSS and its input->output source map
2727
*/
2828
const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
@@ -32,7 +32,8 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
3232
);
3333

3434
// TODO expose the remaining declined transforms on `optimization.minimize.css`
35-
// like `convertLengthUnits`. Each is on in other minifiers; what each costs:
35+
// like `convertLengthUnits` — the switches below turn off what webpack does
36+
// make, not what it declines. Each is on in other minifiers; what each costs:
3637
// - dropping a declaration a later one overrides, which loses a fallback pair
3738
// an engine that cannot read the newer spelling depends on;
3839
// - merging rules a third stands between, and merging non-adjacent `@media`,
@@ -62,7 +63,7 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
6263
// - a pair two shorthands both claim, which cannot be right for both. None
6364
// today: `mdn-data` gave `corner-inline-start-shape` the block-start edge's
6465
// corners, corrected in the generator to the pair Chromium computes.
65-
const { SourceProcessor } = webpack.css.syntax;
66+
const { SourceProcessor, pickTransforms } = webpack.css.syntax;
6667
const [[file, code]] = Object.entries(input);
6768
// `process` parses once, and with `mode: "minify"` the same walk also prints
6869
// the safely minified serialization — no second parse. Naming the input with
@@ -76,7 +77,11 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
7677
content: code,
7778
environment,
7879
convertLengthUnits,
79-
rewriteCustomProperties
80+
rewriteCustomProperties,
81+
// The per-transform switches stand beside those rather than nested in
82+
// them, so a config names one the way it names `convertLengthUnits`;
83+
// `pickTransforms` is what knows which names those are.
84+
transforms: pickTransforms(minimizerOptions)
8085
});
8186
};
8287

0 commit comments

Comments
 (0)