Skip to content

Commit 7f0426b

Browse files
feat(html): minify SVG and XML assets under futureDefaults
Co-authored-by: Alexander Akait <[email protected]>
1 parent 3150b8a commit 7f0426b

16 files changed

Lines changed: 385 additions & 7 deletions

File tree

‎.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 an `xml` mode to `html.syntax` that parses and prints XML.
5+
Add an `xml` mode to `html.syntax` and a futureDefaults SVG/XML minimizer.

‎declarations/WebpackOptions.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3406,8 +3406,21 @@ export interface OptimizationMinimizeOptions {
34063406
* @since 5.112.0
34073407
*/
34083408
json?: boolean;
3409+
/**
3410+
* Minimize `.svg` and `.xml` assets: `false` disables it, an object enables it. Absent means off unless `experiments.futureDefaults` is set.
3411+
* @since 5.112.0
3412+
* @experimental
3413+
*/
3414+
xml?: false | OptimizationMinimizeXml;
34093415
}
34103416

3417+
/**
3418+
* 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.
3419+
* @since 5.112.0
3420+
* @experimental
3421+
*/
3422+
export interface OptimizationMinimizeXml {}
3423+
34113424
/**
34123425
* Enables/Disables integrated optimizations.
34133426
*/

‎lib/config/defaults.js‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2522,6 +2522,7 @@ const applyOptimizationDefaults = (
25222522
F(minimizeOptions, "css", () => ({}));
25232523
F(minimizeOptions, "html", () => ({}));
25242524
D(minimizeOptions, "json", futureDefaults);
2525+
if (futureDefaults) F(minimizeOptions, "xml", () => ({}));
25252526
}
25262527
A(optimization, "minimizer", () => [
25272528
{
@@ -2574,7 +2575,19 @@ const applyOptimizationDefaults = (
25742575
// `=== true` rather than `!== false`: outside `futureDefaults`, JSON is opt-in.
25752576
const minifyJson =
25762577
minimizeByType.json === true && !claimedByOtherMinimizer.json;
2577-
if (!minifyJs && !minifyCss && !minifyHtml && !minifyJson) return;
2578+
// Off unless asked for: only an object, which futureDefaults supplies.
2579+
const minifyXml =
2580+
!claimedByOtherMinimizer.xml &&
2581+
typeof minimizeByType.xml === "object";
2582+
if (
2583+
!minifyJs &&
2584+
!minifyCss &&
2585+
!minifyHtml &&
2586+
!minifyJson &&
2587+
!minifyXml
2588+
) {
2589+
return;
2590+
}
25782591
// An asset name keeps the query and the fragment its filename template
25792592
// wrote (`[query][fragment]`, `main.js#[contenthash]`), so both may follow.
25802593
/**
@@ -2583,7 +2596,13 @@ const applyOptimizationDefaults = (
25832596
*/
25842597
const assetNameTest = (extensions) =>
25852598
new RegExp(`^[^?#]*\\.(?:${extensions.join("|")})(?:[?#].*)?$`, "i");
2586-
if (minifyJs && !minifyCss && !minifyHtml && !minifyJson) {
2599+
if (
2600+
minifyJs &&
2601+
!minifyCss &&
2602+
!minifyHtml &&
2603+
!minifyJson &&
2604+
!minifyXml
2605+
) {
25872606
new MinimizerPlugin({
25882607
test: assetNameTest(["[cm]?js"]),
25892608
minify: javascriptMinify,
@@ -2653,6 +2672,15 @@ const applyOptimizationDefaults = (
26532672
// A web app manifest is JSON under its own extension.
26542673
extensions.push("json", "webmanifest");
26552674
}
2675+
if (minifyXml) {
2676+
minify.push(require.resolve("../html/xmlMinify"));
2677+
minimizerOptions.push({
2678+
environment: cssEnvironment,
2679+
css: cssOptions,
2680+
...minimizeByType.xml
2681+
});
2682+
extensions.push("svg", "xml");
2683+
}
26562684
new MinimizerPlugin({
26572685
test: assetNameTest(extensions),
26582686
minify,

‎lib/config/getClaimedAssetTypes.js‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,14 @@ const claims = (candidate, file) => {
4242
* matcher rather than resolving it per emitted asset, so a minimizer restricted
4343
* to some of a type's files still claims the whole type.
4444
* @param {Compiler} compiler the compiler
45-
* @returns {{ css: boolean, html: boolean, json: boolean }} types another minimizer handles
45+
* @returns {{ css: boolean, html: boolean, json: boolean, xml: boolean }} types another minimizer handles
4646
*/
4747
module.exports = (compiler) => {
4848
const { optimization, plugins } = compiler.options;
4949
let css = false;
5050
let html = false;
5151
let json = false;
52+
let xml = false;
5253
// Both lists are normalized arrays with falsy entries already filtered out,
5354
// and `minimizer` was filled in by the defaults before any plugin applies.
5455
const minimizer =
@@ -62,7 +63,10 @@ module.exports = (compiler) => {
6263
json =
6364
claims(candidate, "file.json") || claims(candidate, "file.webmanifest");
6465
}
65-
if (css && html && json) break;
66+
if (!xml) {
67+
xml = claims(candidate, "file.svg") || claims(candidate, "file.xml");
68+
}
69+
if (css && html && json && xml) break;
6670
}
67-
return { css, html, json };
71+
return { css, html, json, xml };
6872
};

‎lib/html/xmlMinify.js‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author sheo13666q @sheo13666q
4+
*/
5+
6+
"use strict";
7+
8+
/** @import { CssEnvironment } from "../css/syntax-parser" */
9+
/** @import { RawSourceMap } from "webpack-sources" */
10+
11+
/**
12+
* A `minify` function for `minimizer-webpack-plugin`: prints one `.svg` or `.xml`
13+
* asset minified, reading it as XML 1.0 and minifying each SVG or XHTML stylesheet
14+
* it holds with the CSS minifier.
15+
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
16+
* @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 } } }=} minimizerOptions `environment` and `css` (`optimization.minimizeOptions.css`, whole) reach the CSS minifier this runs over each stylesheet
18+
* @returns {Promise<{ code: string }>} the minified document
19+
*/
20+
const xmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
21+
const webpack = /** @type {typeof import("../index")} */ (
22+
// eslint-disable-next-line import/no-extraneous-dependencies -- webpack self-require, re-resolved inside the worker
23+
require(/** @type {string} */ ("webpack"))
24+
);
25+
26+
const [[, given]] = Object.entries(input);
27+
const code = typeof given === "string" ? given : given.toString("utf8");
28+
const { environment, css = {} } = minimizerOptions;
29+
// The same renderer and options HTML hands an inline `<style>`, so a
30+
// stylesheet an SVG holds agrees with the `.css` asset for the same target.
31+
const renderEmbeddedSource = webpack.html.builtinEmbeddedRenderer({
32+
environment,
33+
convertLengthUnits: css.convertLengthUnits,
34+
convertApproximateColors: css.convertApproximateColors,
35+
dropOverriddenDeclarations: css.dropOverriddenDeclarations,
36+
rewriteCustomProperties: css.rewriteCustomProperties,
37+
unusedSymbols: css.unusedSymbols,
38+
pseudoClasses: css.pseudoClasses,
39+
transforms: webpack.css.syntax.parser.pickTransforms(css)
40+
});
41+
return {
42+
code: new webpack.html.syntax.SourceProcessor().process(code, {
43+
xml: true,
44+
mode: "minify",
45+
renderEmbeddedSource
46+
}).code
47+
};
48+
};
49+
50+
// Worker-safe (see the body's in-worker `require`), so it may share the pool.
51+
xmlMinify.supportsWorkerThreads = () => true;
52+
53+
/**
54+
* The language this minifies, for a caller dispatching source with no filename.
55+
* @returns {string[]} the languages
56+
*/
57+
xmlMinify.getTypes = () => ["xml"];
58+
59+
/**
60+
* @param {string} name asset filename
61+
* @returns {boolean} true for SVG and XML assets
62+
*/
63+
xmlMinify.filter = (name) => /^[^?#]*\.(?:svg|xml)(?:[?#].*)?$/i.test(name);
64+
65+
module.exports = xmlMinify;

‎lib/index.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,10 @@ module.exports = mergeExports(fn, {
800800
// `SourceProcessor` / `printer` exports carry the `@experimental` tag).
801801
get syntax() {
802802
return require("./html/syntax");
803+
},
804+
// The minifier `optimization.minimizer` dispatches `.svg` and `.xml` to.
805+
get xmlMinify() {
806+
return require("./html/xmlMinify");
803807
}
804808
},
805809

‎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: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4415,10 +4415,30 @@
44154415
"description": "Minimize JSON assets by re-serializing them without whitespace (defaults to `true` with `experiments.futureDefaults`, otherwise `false`).",
44164416
"type": "boolean",
44174417
"added": "5.112.0"
4418+
},
4419+
"xml": {
4420+
"description": "Minimize `.svg` and `.xml` assets: `false` disables it, an object enables it. Absent means off unless `experiments.futureDefaults` is set.",
4421+
"anyOf": [
4422+
{
4423+
"enum": [false]
4424+
},
4425+
{
4426+
"$ref": "#/definitions/OptimizationMinimizeXml"
4427+
}
4428+
],
4429+
"experimental": true,
4430+
"added": "5.112.0"
44184431
}
44194432
},
44204433
"added": "5.110.0"
44214434
},
4435+
"OptimizationMinimizeXml": {
4436+
"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.",
4437+
"type": "object",
4438+
"additionalProperties": false,
4439+
"experimental": true,
4440+
"added": "5.112.0"
4441+
},
44224442
"OptimizationNormalized": {
44234443
"description": "Enables/Disables integrated optimizations.",
44244444
"type": "object",

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12779,6 +12779,38 @@ Object {
1277912779
"multiple": false,
1278012780
"simpleType": "boolean",
1278112781
},
12782+
"optimization-minimize-options-xml": Object {
12783+
"configs": Array [
12784+
Object {
12785+
"description": "Minimize \`.svg\` and \`.xml\` assets: \`false\` disables it, an object enables it. Absent means off unless \`experiments.futureDefaults\` is set.",
12786+
"multiple": false,
12787+
"path": "optimization.minimizeOptions.xml",
12788+
"type": "enum",
12789+
"values": Array [
12790+
false,
12791+
],
12792+
},
12793+
],
12794+
"description": "Minimize \`.svg\` and \`.xml\` assets: \`false\` disables it, an object enables it. Absent means off unless \`experiments.futureDefaults\` is set.",
12795+
"multiple": false,
12796+
"simpleType": "boolean",
12797+
},
12798+
"optimization-minimize-xml": Object {
12799+
"configs": Array [
12800+
Object {
12801+
"description": "Minimize \`.svg\` and \`.xml\` assets: \`false\` disables it, an object enables it. Absent means off unless \`experiments.futureDefaults\` is set.",
12802+
"multiple": false,
12803+
"path": "optimization.minimize.xml",
12804+
"type": "enum",
12805+
"values": Array [
12806+
false,
12807+
],
12808+
},
12809+
],
12810+
"description": "Minimize \`.svg\` and \`.xml\` assets: \`false\` disables it, an object enables it. Absent means off unless \`experiments.futureDefaults\` is set.",
12811+
"multiple": false,
12812+
"simpleType": "boolean",
12813+
},
1278212814
"optimization-module-ids": Object {
1278312815
"configs": Array [
1278412816
Object {
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: absent 1`] = `
4+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>
5+
<!-- An editor's comment the minified output drops. -->
6+
<svg xmlns=\\"http://www.w3.org/2000/svg\\" viewBox=\\"0 0 10 10\\">
7+
<style>
8+
.dot {
9+
fill: #ff0000;
10+
user-select: none;
11+
}
12+
</style>
13+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\" />
14+
</svg>
15+
"
16+
`;
17+
18+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: claimed 1`] = `"<svg/>"`;
19+
20+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: disabled 1`] = `
21+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>
22+
<!-- An editor's comment the minified output drops. -->
23+
<svg xmlns=\\"http://www.w3.org/2000/svg\\" viewBox=\\"0 0 10 10\\">
24+
<style>
25+
.dot {
26+
fill: #ff0000;
27+
user-select: none;
28+
}
29+
</style>
30+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\" />
31+
</svg>
32+
"
33+
`;
34+
35+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: future 1`] = `
36+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><svg xmlns=\\"http://www.w3.org/2000/svg\\" viewBox=\\"0 0 10 10\\">
37+
<style>.dot{fill:red;-webkit-user-select:none;user-select:none}</style>
38+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
39+
</svg>"
40+
`;
41+
42+
exports[`ConfigCacheTestCases optimization minimize-xml minimize-xml should compile: object 1`] = `
43+
"<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><svg xmlns=\\"http://www.w3.org/2000/svg\\" viewBox=\\"0 0 10 10\\">
44+
<style>.dot{fill:red;-webkit-user-select:none;user-select:none}</style>
45+
<circle class=\\"dot\\" cx=\\"5\\" cy=\\"5\\" r=\\"4\\"/>
46+
</svg>"
47+
`;

0 commit comments

Comments
 (0)