Skip to content

Commit c47e84f

Browse files
feat(xml): support attribute sorting in the shared HTML printer (#22689)
1 parent ea1d93d commit c47e84f

17 files changed

Lines changed: 156 additions & 23 deletions

‎.changeset/020-html-syntax-xml-mode.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-
Add XML parsing and SVG/XML minification, including embedded SVG data URLs.
5+
Add XML parsing and SVG/XML minification with data URLs and attribute sorting.

‎declarations/WebpackOptions.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3448,11 +3448,17 @@ export interface OptimizationMinimizeOptions {
34483448
}
34493449

34503450
/**
3451-
* What the XML minimizer does. It has no switches of its own yet: the stylesheets an SVG or XHTML element holds are minified with `optimization.minimizeOptions.css` for the target's browsers.
3451+
* What the XML minimizer does. The stylesheets an SVG or XHTML element holds are minified with `optimization.minimizeOptions.css` for the target's browsers.
34523452
* @since 5.112.0
34533453
* @experimental
34543454
*/
3455-
export interface OptimizationMinimizeXml {}
3455+
export interface OptimizationMinimizeXml {
3456+
/**
3457+
* Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.
3458+
* @since 5.112.0
3459+
*/
3460+
sortAttributes?: boolean;
3461+
}
34563462

34573463
/**
34583464
* Enables/Disables integrated optimizations.

‎lib/html/syntax-parser.js‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12366,7 +12366,8 @@ const _attributeFrequency = () => {
1236612366
const start = _nodeAttrStarts[node];
1236712367
// Foreign content keeps every attribute it was written with, so only an
1236812368
// HTML element is asked what it drops — the same test the printer makes.
12369-
const html = _namespaceOf(node) === NS_HTML;
12369+
const namespace = _namespaceOf(node);
12370+
const html = namespace === NS_HTML;
1237012371
const elementName = _tagNameOf(node);
1237112372
const markers =
1237212373
html && _S._removeRedundantAttributes !== "none"
@@ -12378,6 +12379,7 @@ const _attributeFrequency = () => {
1237812379
: undefined;
1237912380
const mayDrop = markers !== undefined || defaults !== undefined;
1238012381
for (let i = start; i < start + count; i++) {
12382+
if (namespace === NS_XML && _attrNameStarts[i] === -1) continue;
1238112383
const name = _attrNames[i];
1238212384
if (html) {
1238312385
// Valueless reads as the empty value here as it does there.
@@ -12405,9 +12407,7 @@ const _attributeFrequency = () => {
1240512407

1240612408
/**
1240712409
* The element's attribute indices in the order `sortAttributes` prints them:
12408-
* the document's commonest names first, ties by name. Nothing in HTML reads
12409-
* attribute order, so a stable spelling across pages is worth the repeats it
12410-
* hands a compressor.
12410+
* the document's commonest names first, ties by name.
1241112411
* @param {HtmlPath} path the accessor positioned on the element
1241212412
* @param {number} count its attribute count
1241312413
* @returns {number[]} the indices, in print order
@@ -13319,10 +13319,14 @@ const _xmlOpenTag = (path, minify) => {
1331913319
}
1332013320
let out = `<${_tagNameOf(node)}`;
1332113321
const start = _nodeAttrStarts[node];
13322+
const count = _nodeAttrCounts[node];
13323+
const order =
13324+
_sortAttributes && count > 1 ? _sortedAttributes(path, count) : null;
1332213325
const rendering =
1332313326
_S._renderEmbeddedSource !== undefined ||
1332413327
_S._deferEmbeddedSource !== undefined;
13325-
for (let i = start; i < start + _nodeAttrCounts[node]; i++) {
13328+
for (let index = 0; index < count; index++) {
13329+
const i = start + (order === null ? index : order[index]);
1332613330
// A default the DTD supplies is the DTD's to keep supplying.
1332713331
if (_attrNameStarts[i] === -1) continue;
1332813332
const raw = _attrValueOf(i);

‎lib/html/syntax-printer.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ const CLASSIC_SCRIPT = "script";
136136
* @property {boolean=} removeEmptyElements drop an element with no children and no attributes, unless its bare form is meaningful (default false)
137137
* @property {boolean=} mergeStyles print a run of adjacent `<style>` elements as one sheet, which removes elements (default false)
138138
* @property {boolean=} mergeScripts print a run of adjacent bare `<script>` elements whose bodies this print writes itself as one, which removes elements, hoists a later body's declarations into the ones before it, and lets a failing body end the whole run (default false)
139-
* @property {boolean=} sortAttributes print an element's attributes commonest name first, ties by name, which nothing in HTML reads (default false)
139+
* @property {boolean=} sortAttributes print an HTML or XML element's attributes commonest name first, ties by name (default false)
140140
* @property {boolean=} sortTokenLists print every token list the DOM reads as a set (`class`, `rel`, `part`, …) in token order (default false)
141141
* @property {(boolean | "smart" | "all")=} removeRedundantAttributes drop an attribute whose value is the element's own default; `true` is `"smart"`, and `"all"` also drops the spec defaults a selector can match, and with them a value naming no keyword where that says the same (default false)
142142
* @property {(boolean | "smart" | "all")=} removeImpliedTags how much of the `<html>` / `<head>` / `<body>` shell §13.1.2.4 lets the parser imply may be left out: `"smart"` leaves out only the `<html>` start tag, `true` (or `"all"`) all six, `false` none (default `"smart"`)

‎lib/html/xmlMinify.js‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"use strict";
77

88
/** @import { CssEnvironment, CssTransformOptions } from "../css/syntax-parser" */
9+
/** @import { OptimizationMinimizeXml } from "../../declarations/WebpackOptions" */
910
/** @import { RawSourceMap } from "webpack-sources" */
1011

1112
/**
@@ -14,7 +15,7 @@
1415
* it holds with the CSS minifier.
1516
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
1617
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: the printer is token-coarse, so no map is produced)
17-
* @param {{ environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, convertApproximateColors?: boolean, dropOverriddenDeclarations?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } } & CssTransformOptions }=} minimizerOptions `environment` and `css` (`optimization.minimizeOptions.css`, whole) reach the CSS minifier this runs over each stylesheet
18+
* @param {OptimizationMinimizeXml & { environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, convertApproximateColors?: boolean, dropOverriddenDeclarations?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } } & CssTransformOptions }=} minimizerOptions `environment` and `css` (`optimization.minimizeOptions.css`, whole) reach the CSS minifier this runs over each stylesheet
1819
* @returns {Promise<{ code: string }>} the minified document
1920
*/
2021
const xmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -25,7 +26,7 @@ const xmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
2526

2627
const [[, given]] = Object.entries(input);
2728
const code = typeof given === "string" ? given : given.toString("utf8");
28-
const { environment, css = {} } = minimizerOptions;
29+
const { environment, css = {}, sortAttributes } = minimizerOptions;
2930
// The same renderer and options HTML hands an inline `<style>`, so a
3031
// stylesheet an SVG holds agrees with the `.css` asset for the same target.
3132
const renderEmbeddedSource = webpack.html.builtinEmbeddedRenderer({
@@ -42,6 +43,7 @@ const xmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
4243
code: new webpack.html.syntax.SourceProcessor().process(code, {
4344
xml: true,
4445
mode: "minify",
46+
sortAttributes,
4547
renderEmbeddedSource
4648
}).code
4749
};

‎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: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4493,9 +4493,16 @@
44934493
"added": "5.110.0"
44944494
},
44954495
"OptimizationMinimizeXml": {
4496-
"description": "What the XML minimizer does. It has no switches of its own yet: the stylesheets an SVG or XHTML element holds are minified with `optimization.minimizeOptions.css` for the target's browsers.",
4496+
"description": "What the XML minimizer does. The stylesheets an SVG or XHTML element holds are minified with `optimization.minimizeOptions.css` for the target's browsers.",
44974497
"type": "object",
44984498
"additionalProperties": false,
4499+
"properties": {
4500+
"sortAttributes": {
4501+
"description": "Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.",
4502+
"type": "boolean",
4503+
"added": "5.112.0"
4504+
}
4505+
},
44994506
"experimental": true,
45004507
"added": "5.112.0"
45014508
},

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12893,6 +12893,19 @@ Object {
1289312893
"multiple": false,
1289412894
"simpleType": "boolean",
1289512895
},
12896+
"optimization-minimize-options-xml-sort-attributes": Object {
12897+
"configs": Array [
12898+
Object {
12899+
"description": "Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.",
12900+
"multiple": false,
12901+
"path": "optimization.minimizeOptions.xml.sortAttributes",
12902+
"type": "boolean",
12903+
},
12904+
],
12905+
"description": "Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.",
12906+
"multiple": false,
12907+
"simpleType": "boolean",
12908+
},
1289612909
"optimization-minimize-xml": Object {
1289712910
"configs": Array [
1289812911
Object {
@@ -12909,6 +12922,19 @@ Object {
1290912922
"multiple": false,
1291012923
"simpleType": "boolean",
1291112924
},
12925+
"optimization-minimize-xml-sort-attributes": Object {
12926+
"configs": Array [
12927+
Object {
12928+
"description": "Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.",
12929+
"multiple": false,
12930+
"path": "optimization.minimize.xml.sortAttributes",
12931+
"type": "boolean",
12932+
},
12933+
],
12934+
"description": "Print attributes with the document's commonest names first, breaking ties by case-sensitive name. Off by default: consumers observing attribute order see the new order.",
12935+
"multiple": false,
12936+
"simpleType": "boolean",
12937+
},
1291212938
"optimization-module-ids": Object {
1291312939
"configs": Array [
1291412940
Object {

‎test/configCases/optimization/minimize-xml/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,10 @@ exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should comp
6060
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
6161
</svg>"
6262
`;
63+
64+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: sorted 1`] = `
65+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><svg viewBox=\\"0 0 10 10\\" xmlns=\\"http://www.w3.org/2000/svg\\">
66+
<style>.dot{fill:red;-webkit-user-select:none;user-select:none}</style>
67+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
68+
</svg>"
69+
`;

‎test/configCases/optimization/minimize-xml/__snapshots__/ConfigTest.snap‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,10 @@ exports[`ConfigTestCases optimization minimize-xml minimize-xml should compile:
6060
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
6161
</svg>"
6262
`;
63+
64+
exports[`ConfigTestCases optimization minimize-xml minimize-xml should compile: sorted 1`] = `
65+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><svg viewBox=\\"0 0 10 10\\" xmlns=\\"http://www.w3.org/2000/svg\\">
66+
<style>.dot{fill:red;-webkit-user-select:none;user-select:none}</style>
67+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
68+
</svg>"
69+
`;

0 commit comments

Comments
 (0)