Skip to content

Commit d3df6b7

Browse files
feat(css): offer dropping an overridden declaration with no target named
Only the last of a set of declarations of one property can be read, so the earlier carry nothing — but an earlier one differently spelled is usually a fallback, and dropping it is how a `color(display-p3 …)` pair is lost. With a `browserslist` selection that is answerable and already answered: the drop is made wherever every browser named is known to read the later value. With no selection there are no engines to name, so nothing was dropped at all, where csso and cssnano drop unconditionally. `optimization.minimize.css.dropOverriddenDeclarations`, off by default, is how a build says to assume it. It reaches one line — `_valueReadByTarget` answers with the option rather than `false` where no selection was made — so everything the drop already declines it declines still. What it does not do is override a target that was named. A selection saying the later value is unreadable keeps the fallback whatever the option says, and one naming a browser no compat dataset covers still answers for less than the whole of it and keeps it too: naming a browser states a target, and the option assumes one only where none was stated. Forwarded to the CSS minifier the HTML minifier nests, so an inline `<style>` and a `style=""` are held to the same rule as a `.css` asset.
1 parent 1d75746 commit d3df6b7

19 files changed

Lines changed: 205 additions & 14 deletions

File tree

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 `optimization.minimize.css.dropOverriddenDeclarations`, dropping a declaration a later one overrides where no target is named.

‎lib/css/cssMinify.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
* re-resolves in the worker — via the installed package, or the dev self-link.
3434
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3535
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
36-
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & 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). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output
36+
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, dropOverriddenDeclarations?: boolean, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & 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). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output
3737
* @returns {Promise<{ code: string, map?: SourceMap, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified CSS, its input->output source map (one anchor for the whole of a `block-contents` print, which is emitted as one piece), and what a renderer reported over what this embeds
3838
*/
3939
const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -95,6 +95,7 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
9595
as,
9696
environment,
9797
convertLengthUnits,
98+
dropOverriddenDeclarations,
9899
mergeDistantRules,
99100
rewriteCustomProperties,
100101
unusedSymbols,
@@ -111,6 +112,7 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
111112
content: code,
112113
environment,
113114
convertLengthUnits,
115+
dropOverriddenDeclarations,
114116
mergeDistantRules,
115117
rewriteCustomProperties,
116118
unusedSymbols,

‎lib/css/syntax.js‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2048,6 +2048,7 @@ const _setupParse = (input, lc) => {
20482048
_transforms = _DEFAULT_TRANSFORMS;
20492049
_commentsKept = "some";
20502050
_rewriteCustomProperties = false;
2051+
_dropOverriddenDeclarations = false;
20512052
_unitScale = ABSOLUTE_UNIT_SCALE;
20522053
// Back to what the module loads with, so no parse inherits a target of its own.
20532054
_hexAlphaAllowed = true;
@@ -4117,6 +4118,7 @@ const TOP_LEVEL_CONSUMERS = {
41174118
* @property {CssEnvironment=} environment what the target can read (the CSS entries of `output.environment`), so a spelling it would not understand is never reached for; only read while printing, and an absent entry means the modern spelling is available
41184119
* @property {boolean=} convertLengthUnits rewrite a length into a shorter unit it is exactly equal in (`16px` -> `1pc`); off by default because it earns nothing once the asset is compressed, and only read while printing. A time is always rewritten
41194120
* @property {boolean=} mergeDistantRules give a rule the selectors of a later one printing the same block, past the rules between them; off by default, since it reorders the cascade and is sound only where nothing between declares what the block does
4121+
* @property {boolean=} dropOverriddenDeclarations drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value; off by default, and only read while printing. With a `browserslist` selection the drop is already made wherever every browser it names is known to read the later value, so this widens the case where no target is selected — a selection naming a browser the tables do not cover still answers for the whole of it
41204122
* @property {boolean=} rewriteCustomProperties shorten a custom property's value the way any other value is shortened (`--x:#ffffff` -> `#fff`); off by default because `getPropertyValue()` hands that text back, and only read while printing. What it may rewrite is what any other value's tokens may be, a color in a substitution's fallback included — that being the property's value rather than the function's own argument
41214123
* @property {EmbeddedSourceRenderer=} renderEmbeddedSource renders source this stylesheet embeds: the payload of a `url()` `data:` URL whose media type names a language webpack knows (SVG, CSS, HTML, JSON, JavaScript). Absent, a data URL is emitted exactly as written
41224124
* @property {{ [name: string]: string }=} pseudoClasses each pseudo-class to write as a class instead (`{ "focus-visible": "focus-visible" }`), so a script can apply it where the engine does not. Only read while printing
@@ -6724,6 +6726,8 @@ const grammar = (input, visitors, writer, options) => {
67246726
writer !== undefined && writer.options.mergeDistantRules === true;
67256727
_rewriteCustomProperties =
67266728
writer !== undefined && writer.options.rewriteCustomProperties === true;
6729+
_dropOverriddenDeclarations =
6730+
writer !== undefined && writer.options.dropOverriddenDeclarations === true;
67276731
// `_setupParse` left the default in place: only a caller's switches resolve.
67286732
if (writer !== undefined && writer.options.transforms !== undefined) {
67296733
_transforms = _transformsFrom(writer.options.transforms);
@@ -7004,7 +7008,7 @@ const _dropSeparatorAfter = (cc) =>
70047008
* What the CSS printer may be told, on top of the `mode` every language has —
70057009
* the printing slice of `CssProcessOptions`, named once so nothing outside CSS
70067010
* has to enumerate it.
7007-
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
7011+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "dropOverriddenDeclarations" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
70087012
*/
70097013

70107014
/** @typedef {import("../util/SourceProcessor").PrintContext<CssPath, Node, CssPrintOptions>} PrintContext */
@@ -14412,10 +14416,13 @@ const _familyValue = (property, longhands, values) => {
1441214416
* @returns {boolean} true when no target is left reading the earlier one
1441314417
*/
1441414418
const _valueReadByTarget = (property, value) => {
14415-
// No selection names no browser to answer for, and one naming a browser the
14416-
// tables do not cover answers for less than the whole of it; either way
14417-
// nothing is known to read the later value and the earlier one stands.
14418-
if (_prefixBrowsers === null || _someBrowserUnanswered) return false;
14419+
// No selection names no browser to answer for, so nothing is known to read the
14420+
// later value: the earlier one stands unless asked to assume otherwise.
14421+
if (_prefixBrowsers === null) return _dropOverriddenDeclarations;
14422+
// A selection naming a browser the tables do not cover answers for less than
14423+
// the whole of it. Naming a browser states a target, which the option that
14424+
// assumes one does not override, so this stands whatever it says.
14425+
if (_someBrowserUnanswered) return false;
1441914426
const open = value.indexOf("(");
1442014427
if (open === -1) {
1442114428
return _readsAll(
@@ -16745,9 +16752,9 @@ const _composeBlockBody = (
1674516752
// (`_valueReadByTarget`), since otherwise the earlier is its fallback —
1674616753
// dropping those is how esbuild and lightningcss lose a `color(display-p3 …)`
1674716754
// pair.
16748-
// TODO answer the same question with no browserslist selection, as csso and
16749-
// cssnano do: theirs is unconditional, and naming the engines is what makes
16750-
// this one sound — with no selection there are none to name.
16755+
// With no selection there are no engines to name, so the same question is
16756+
// answered only where `dropOverriddenDeclarations` asks for it — csso and
16757+
// cssnano answer it unconditionally, and give up the same fallback pair.
1675116758
/** @type {Set<number> | null} */
1675216759
let superseded = null;
1675316760
// CSS Animations 1 §3: a keyframe ignores an `!important` declaration, so one
@@ -18101,6 +18108,10 @@ let _inCustomProperty = false;
1810118108
// Off, that verbatim rule stands; on, a custom property's tokens print like any
1810218109
// other value's and `getPropertyValue()` hands back the rewritten text.
1810318110
let _rewriteCustomProperties = false;
18111+
// Whether a declaration a later one overrides is dropped with no `browserslist`
18112+
// selection to say the later value is readable. Off by default: it gives up the
18113+
// fallback pair an engine that cannot read the later spelling depends on.
18114+
let _dropOverriddenDeclarations = false;
1810418115
let _inSubstitutedValue = false;
1810518116
// Inside a color the engine computes with rather than paints.
1810618117

‎lib/html/builtinEmbeddedRenderer.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
1313
/**
1414
* What this minifies inline CSS with: the CSS minifier's own options, so an
1515
* inline declaration is held to the rules a `.css` asset is.
16-
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "rewriteCustomProperties" | "transforms" | "unusedSymbols" | "pseudoClasses">} BuiltinEmbeddedRendererOptions
16+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "dropOverriddenDeclarations" | "rewriteCustomProperties" | "transforms" | "unusedSymbols" | "pseudoClasses">} BuiltinEmbeddedRendererOptions
1717
*/
1818

1919
// Both are loaded on first render rather than at module load: a document that

‎lib/html/htmlMinify.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
* re-resolves in the worker — via the installed package, or the dev self-link.
3636
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3737
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
38-
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output. What it declines this minifies itself, for the languages webpack ships a minifier for
38+
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, dropOverriddenDeclarations?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output. What it declines this minifies itself, for the languages webpack ships a minifier for
3939
* @returns {Promise<{ code: string, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified HTML, and what a renderer reported over what it embeds
4040
*/
4141
const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -83,6 +83,7 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
8383
const builtin = builtinEmbeddedRenderer({
8484
environment,
8585
convertLengthUnits: css.convertLengthUnits,
86+
dropOverriddenDeclarations: css.dropOverriddenDeclarations,
8687
rewriteCustomProperties: css.rewriteCustomProperties,
8788
unusedSymbols: css.unusedSymbols,
8889
pseudoClasses: css.pseudoClasses,

‎schemas/WebpackOptions.check.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎schemas/WebpackOptions.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4019,6 +4019,11 @@
40194019
"type": "boolean",
40204020
"added": "5.110.0"
40214021
},
4022+
"dropOverriddenDeclarations": {
4023+
"description": "Drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value. Off by default. With a `browserslist` target this is already done wherever every browser it names is known to read the later value, so the option only widens the case where no target is selected and there are no engines to name \u2014 which is what csso and cssnano do unconditionally. What it gives up is the fallback pair: `color:#c65d06;color:lab(50% 100 -100)` loses the hex, so an engine that cannot read `lab()` is left with nothing. A selection naming a browser the compat tables do not cover is still answered for the whole of it rather than by this option, since naming a browser states a target the option does not override.",
4024+
"type": "boolean",
4025+
"added": "5.112.0"
4026+
},
40224027
"foldCase": {
40234028
"description": "Write a name that matches ASCII case-insensitively in lowercase: an at-rule name, a property name, a pseudo-class or pseudo-element name, a function name, a unit, and a keyword standing in a value whose grammar takes keywords alone. `@MEDIA`, `COLOR`, `:NTH-CHILD`, `URL(`, `1PX` and `currentColor` become `@media`, `color`, `:nth-child`, `url(`, `1px` and `currentcolor`. On by default, and exact: CSS matches every one of these ASCII case-insensitively, so the fold names the same thing. What it never touches is a name the author chose — a custom property, a custom ident such as an animation or grid-area name, an id, a class, a type selector, an attribute's value, or anything inside a substituted value. `@charset` is left as written, being read as bytes rather than matched, and `!important` is always written in lowercase because the printer writes the keyword rather than copying it.",
40244029
"type": "boolean",

‎test/__snapshots__/Cli.basictest.js.snap‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11189,6 +11189,19 @@ Object {
1118911189
"multiple": false,
1119011190
"simpleType": "boolean",
1119111191
},
11192+
"optimization-minimize-css-drop-overridden-declarations": Object {
11193+
"configs": Array [
11194+
Object {
11195+
"description": "Drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value. Off by default. With a \`browserslist\` target this is already done wherever every browser it names is known to read the later value, so the option only widens the case where no target is selected and there are no engines to name — which is what csso and cssnano do unconditionally. What it gives up is the fallback pair: \`color:#c65d06;color:lab(50% 100 -100)\` loses the hex, so an engine that cannot read \`lab()\` is left with nothing. A selection naming a browser the compat tables do not cover is still answered for the whole of it rather than by this option, since naming a browser states a target the option does not override.",
11196+
"multiple": false,
11197+
"path": "optimization.minimize.css.dropOverriddenDeclarations",
11198+
"type": "boolean",
11199+
},
11200+
],
11201+
"description": "Drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value. Off by default. With a \`browserslist\` target this is already done wherever every browser it names is known to read the later value, so the option only widens the case where no target is selected and there are no engines to name — which is what csso and cssnano do unconditionally. What it gives up is the fallback pair: \`color:#c65d06;color:lab(50% 100 -100)\` loses the hex, so an engine that cannot read \`lab()\` is left with nothing. A selection naming a browser the compat tables do not cover is still answered for the whole of it rather than by this option, since naming a browser states a target the option does not override.",
11202+
"multiple": false,
11203+
"simpleType": "boolean",
11204+
},
1119211205
"optimization-minimize-css-fold-case": Object {
1119311206
"configs": Array [
1119411207
Object {
@@ -11854,6 +11867,19 @@ Object {
1185411867
"multiple": false,
1185511868
"simpleType": "boolean",
1185611869
},
11870+
"optimization-minimize-options-css-drop-overridden-declarations": Object {
11871+
"configs": Array [
11872+
Object {
11873+
"description": "Drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value. Off by default. With a \`browserslist\` target this is already done wherever every browser it names is known to read the later value, so the option only widens the case where no target is selected and there are no engines to name — which is what csso and cssnano do unconditionally. What it gives up is the fallback pair: \`color:#c65d06;color:lab(50% 100 -100)\` loses the hex, so an engine that cannot read \`lab()\` is left with nothing. A selection naming a browser the compat tables do not cover is still answered for the whole of it rather than by this option, since naming a browser states a target the option does not override.",
11874+
"multiple": false,
11875+
"path": "optimization.minimizeOptions.css.dropOverriddenDeclarations",
11876+
"type": "boolean",
11877+
},
11878+
],
11879+
"description": "Drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value. Off by default. With a \`browserslist\` target this is already done wherever every browser it names is known to read the later value, so the option only widens the case where no target is selected and there are no engines to name — which is what csso and cssnano do unconditionally. What it gives up is the fallback pair: \`color:#c65d06;color:lab(50% 100 -100)\` loses the hex, so an engine that cannot read \`lab()\` is left with nothing. A selection naming a browser the compat tables do not cover is still answered for the whole of it rather than by this option, since naming a browser states a target the option does not override.",
11880+
"multiple": false,
11881+
"simpleType": "boolean",
11882+
},
1185711883
"optimization-minimize-options-css-fold-case": Object {
1185811884
"configs": Array [
1185911885
Object {
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases css minimize-drop-overridden-declarations minimize-drop-overridden-declarations should compile 1`] = `
4+
Array [
5+
"/*! the hex before it goes, though nothing here states \`lab()\` can be read */.t01{color:lab(50% 100 -100)}",
6+
"/*! a keyword the property's own grammar names is the same question */.t02{display:flex}",
7+
"/*! ...and a value no table could answer for */.t03{color:var(--brand)}",
8+
"/*! ...and one spelled in a way that is not a fallback at all */.t04{margin-top:2px}",
9+
"/*! an earlier \`!important\` is not overridden by a later plain one */.t10{color:red!important;color:blue}",
10+
"/*! ...but a later \`!important\` does override an earlier plain one */.t11{color:blue!important}",
11+
"/*! a custom property's value is handed back by \`getPropertyValue()\`, so the
12+
pair stands whatever this option says */.t12{--x:red;--x:lab(50% 100 -100)}",
13+
"/*! a rule between them parts the two, so neither overrides the other */.t13{color:red;& .inner{color:lime}color:blue}",
14+
"/*! a keyframe ignores \`!important\`, so one there stands over nothing */@keyframes t14{0%{color:red!important;color:blue}}",
15+
]
16+
`;

0 commit comments

Comments
 (0)