Skip to content

Commit 7606cb0

Browse files
committed
feat: accept an object for optimization.minimize
Carries what a minimizer may do beyond the transforms that always apply, starting with html.collapseWhitespace: each run of whitespace in text becomes a single space, never nothing — removing it joins two inline elements that render apart. Skipped under pre/textarea/listing and for text holding a '<', which stays on the source-passthrough path.
1 parent e048e5f commit 7606cb0

15 files changed

Lines changed: 300 additions & 21 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+
Accept an object for `optimization.minimize`, carrying what a minimizer may do beyond the always-safe transforms — starting with `html.collapseWhitespace`.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2270,9 +2270,16 @@ export interface Optimization {
22702270
*/
22712271
mergeDuplicateChunks?: boolean;
22722272
/**
2273-
* Enable minimizing the output. Uses optimization.minimizer.
2273+
* Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.
22742274
*/
2275-
minimize?: boolean;
2275+
minimize?:
2276+
| boolean
2277+
| {
2278+
/**
2279+
* What the HTML minimizer may do beyond the transforms that always apply.
2280+
*/
2281+
html?: OptimizationMinimizeHtml;
2282+
};
22762283
/**
22772284
* Minimizer(s) to use for minimizing the output.
22782285
*/
@@ -2337,6 +2344,17 @@ export interface ConcatenateModulesOptions {
23372344
*/
23382345
commonjs?: boolean;
23392346
}
2347+
/**
2348+
* What the HTML minimizer may do beyond the transforms that always apply.
2349+
* @since 5.110.0
2350+
*/
2351+
export interface OptimizationMinimizeHtml {
2352+
/**
2353+
* Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace is significant, and never removed entirely — dropping it would join two inline elements that render apart.
2354+
* @since 5.110.0
2355+
*/
2356+
collapseWhitespace?: boolean;
2357+
}
23402358
/**
23412359
* Plugin instance.
23422360
*/
@@ -4424,9 +4442,17 @@ export interface OptimizationNormalized {
44244442
*/
44254443
mergeDuplicateChunks?: boolean;
44264444
/**
4427-
* Enable minimizing the output. Uses optimization.minimizer.
4445+
* Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.
44284446
*/
4429-
minimize?: boolean;
4447+
minimize?:
4448+
| boolean
4449+
| {
4450+
/**
4451+
* What the HTML minimizer may do beyond the transforms that always apply.
4452+
* @since 5.110.0
4453+
*/
4454+
html?: OptimizationMinimizeHtml;
4455+
};
44304456
/**
44314457
* Minimizer(s) to use for minimizing the output.
44324458
*/

‎lib/config/defaults.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2473,8 +2473,14 @@ const applyOptimizationDefaults = (
24732473
minimizerOptions.push({ environment: cssEnvironment });
24742474
}
24752475
if (minifyHtml) {
2476+
// `optimization.minimize` as an object carries what each minimizer
2477+
// may do beyond the transforms that always apply.
2478+
const { minimize } = compiler.options.optimization;
24762479
minify.push(require("../html/htmlMinify"));
2477-
minimizerOptions.push({ environment: cssEnvironment });
2480+
minimizerOptions.push({
2481+
environment: cssEnvironment,
2482+
...(typeof minimize === "object" ? minimize.html : undefined)
2483+
});
24782484
}
24792485
while (minimizerOptions.length < minify.length) {
24802486
minimizerOptions.push({});

‎lib/html/htmlMinify.js‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,15 +55,17 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
5555
// An inline `<style>` or `style=""` runs through the CSS minifier, so it needs
5656
// the same target abilities a `.css` asset gets — without them the two would
5757
// disagree on a hex alpha, `inset` or a media range.
58-
const { environment } = /** @type {{ environment?: CssEnvironment }} */ (
59-
minimizerOptions
60-
);
58+
const { environment, collapseWhitespace } =
59+
/** @type {{ environment?: CssEnvironment, collapseWhitespace?: boolean }} */ (
60+
minimizerOptions
61+
);
6162
// `process` parses once, and with `minimize` its walk also prints the safely
6263
// minified serialization — no second parse. It returns `{ code, map }`, but the
6364
// HTML serialize is token-coarse so the map has no mappings; only the code is used.
6465
const { code: out } = new SourceProcessor().process(code, {
6566
minimize: true,
66-
environment
67+
environment,
68+
collapseWhitespace
6769
});
6870
return { code: out };
6971
};

‎lib/html/syntax.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5165,6 +5165,36 @@ const isAllWs = (/** @type {string} */ s) => {
51655165
return true;
51665166
};
51675167

5168+
/**
5169+
* Collapse every run of HTML whitespace to one space. A run is never removed
5170+
* outright: `a <b>c</b>` and `a<b>c</b>` render differently, and the printer
5171+
* cannot see a `white-space` declaration that would make the rest significant.
5172+
* @param {string} s text data
5173+
* @returns {string} the collapsed text
5174+
*/
5175+
const collapseWs = (s) => {
5176+
let out = "";
5177+
let last = 0;
5178+
let run = -1;
5179+
for (let i = 0; i <= s.length; i++) {
5180+
const c = i === s.length ? 0 : s.charCodeAt(i);
5181+
const ws =
5182+
c === 0x09 || c === 0x0a || c === 0x0c || c === 0x0d || c === 0x20;
5183+
if (ws) {
5184+
if (run === -1) run = i;
5185+
continue;
5186+
}
5187+
// A one-character run is already a single space unless it is a tab or a
5188+
// newline, which still print shorter as one.
5189+
if (run !== -1 && (i - run > 1 || s.charCodeAt(run) !== 0x20)) {
5190+
out += `${s.slice(last, run)} `;
5191+
last = i;
5192+
}
5193+
run = -1;
5194+
}
5195+
return last === 0 ? s : out + s.slice(last);
5196+
};
5197+
51685198
const mathmlTextIntegrationPoint = (/** @type {HtmlElement} */ el) =>
51695199
_namespaceOf(el) === NS_MATHML && MATHML_TEXT_INTEGRATION.has(_tagNameOf(el));
51705200

@@ -7853,6 +7883,7 @@ const parseDoctype = (/** @type {string} */ raw) => {
78537883
* @property {HtmlAstSkip=} skip node kinds to omit from the AST for speed/memory (see `HtmlAstSkip`)
78547884
* @property {boolean=} minimize print the safely-minified serialization (nodes rebuilt from source, inert comments dropped, opening-tag whitespace collapsed) as `process` walks, and return it (default false = walk only, return `""`)
78557885
* @property {CssEnvironment=} environment what the target can read, forwarded to the CSS minifier this runs over an inline `<style>` and every `style=""`
7886+
* @property {boolean=} collapseWhitespace collapse each run of whitespace in text to a single space, except where an ancestor renders it verbatim (default false)
78567887
*/
78577888

78587889
/** @typedef {import("../util/SourceProcessor").PrintContext<HtmlPath, HtmlNodeRef>} PrintContext */
@@ -8096,6 +8127,10 @@ const _canOmitColgroupStart = (path, node) => {
80968127
/** @type {CssEnvironment | undefined} */
80978128
let _cssEnvironment;
80988129

8130+
// Whether text whitespace may be collapsed (see `HtmlProcessOptions`). Set per
8131+
// parse, like `_cssEnvironment`.
8132+
let _collapseWhitespace = false;
8133+
80998134
/**
81008135
* Minify a `<style>` body with webpack's own CSS minifier — the one that runs on
81018136
* CSS assets, so an inline sheet is held to the same rules. Anything it rejects
@@ -8742,6 +8777,27 @@ const printer = (path, writer) => {
87428777
) {
87438778
return "";
87448779
}
8780+
// A `<` puts the node on the source-passthrough path below, which is what
8781+
// keeps `<%= x %>` off the escaper — worth more than the whitespace.
8782+
if (minify && _collapseWhitespace && !data.includes("<")) {
8783+
// `white-space: pre` is invisible from here, so only the elements that
8784+
// render whitespace verbatim without any CSS are excluded — and by
8785+
// ancestor, since the property inherits.
8786+
let preformatted = false;
8787+
for (let a = parent; a !== 0; a = path.parentOf(a)) {
8788+
if (
8789+
path.namespace(a) === NS_HTML &&
8790+
LEADING_NEWLINE_ELEMENTS.has(path.tagName(a))
8791+
) {
8792+
preformatted = true;
8793+
break;
8794+
}
8795+
}
8796+
if (!preformatted) {
8797+
const collapsed = collapseWs(data);
8798+
if (collapsed !== data) return _escapeTextContent(collapsed, minify);
8799+
}
8800+
}
87458801
const raw = path.source();
87468802
// Off-spec workaround: §13.3 escapes `<`/`>` in text, which would rewrite
87478803
// `<%= x %>` to `&lt;%= x %&gt;` in HTML webpack only passes through. Text
@@ -8804,6 +8860,7 @@ const printer = (path, writer) => {
88048860
* @param {HtmlProcessOptions} options process options
88058861
*/
88068862
const grammar = (input, visitors, writer, options) => {
8863+
_collapseWhitespace = options.collapseWhitespace === true;
88078864
const root = parseHtml(input, 0, options);
88088865

88098866
// Iterative depth-first walk over the link columns: `firstChild`

‎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: 43 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3569,8 +3569,21 @@
35693569
"type": "boolean"
35703570
},
35713571
"minimize": {
3572-
"description": "Enable minimizing the output. Uses optimization.minimizer.",
3573-
"type": "boolean"
3572+
"description": "Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.",
3573+
"anyOf": [
3574+
{
3575+
"type": "boolean"
3576+
},
3577+
{
3578+
"type": "object",
3579+
"additionalProperties": false,
3580+
"properties": {
3581+
"html": {
3582+
"$ref": "#/definitions/OptimizationMinimizeHtml"
3583+
}
3584+
}
3585+
}
3586+
]
35743587
},
35753588
"minimizer": {
35763589
"description": "Minimizer(s) to use for minimizing the output.",
@@ -3677,6 +3690,19 @@
36773690
}
36783691
}
36793692
},
3693+
"OptimizationMinimizeHtml": {
3694+
"description": "What the HTML minimizer may do beyond the transforms that always apply.",
3695+
"type": "object",
3696+
"additionalProperties": false,
3697+
"properties": {
3698+
"collapseWhitespace": {
3699+
"description": "Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace is significant, and never removed entirely — dropping it would join two inline elements that render apart.",
3700+
"type": "boolean",
3701+
"added": "5.110.0"
3702+
}
3703+
},
3704+
"added": "5.110.0"
3705+
},
36803706
"OptimizationNormalized": {
36813707
"description": "Enables/Disables integrated optimizations.",
36823708
"type": "object",
@@ -3748,8 +3774,21 @@
37483774
"type": "boolean"
37493775
},
37503776
"minimize": {
3751-
"description": "Enable minimizing the output. Uses optimization.minimizer.",
3752-
"type": "boolean"
3777+
"description": "Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.",
3778+
"anyOf": [
3779+
{
3780+
"type": "boolean"
3781+
},
3782+
{
3783+
"type": "object",
3784+
"additionalProperties": false,
3785+
"properties": {
3786+
"html": {
3787+
"$ref": "#/definitions/OptimizationMinimizeHtml"
3788+
}
3789+
}
3790+
}
3791+
]
37533792
},
37543793
"minimizer": {
37553794
"description": "Minimizer(s) to use for minimizing the output.",

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9920,13 +9920,26 @@ Object {
99209920
"optimization-minimize": Object {
99219921
"configs": Array [
99229922
Object {
9923-
"description": "Enable minimizing the output. Uses optimization.minimizer.",
9923+
"description": "Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.",
99249924
"multiple": false,
99259925
"path": "optimization.minimize",
99269926
"type": "boolean",
99279927
},
99289928
],
9929-
"description": "Enable minimizing the output. Uses optimization.minimizer.",
9929+
"description": "Enable minimizing the output. Uses optimization.minimizer. An object enables it and configures what a minimizer may do beyond the transforms that always apply.",
9930+
"multiple": false,
9931+
"simpleType": "boolean",
9932+
},
9933+
"optimization-minimize-html-collapse-whitespace": Object {
9934+
"configs": Array [
9935+
Object {
9936+
"description": "Collapse each run of whitespace in text to a single space. Left alone inside \`pre\`, \`textarea\` and \`listing\`, where whitespace is significant, and never removed entirely — dropping it would join two inline elements that render apart.",
9937+
"multiple": false,
9938+
"path": "optimization.minimize.html.collapseWhitespace",
9939+
"type": "boolean",
9940+
},
9941+
],
9942+
"description": "Collapse each run of whitespace in text to a single space. Left alone inside \`pre\`, \`textarea\` and \`listing\`, where whitespace is significant, and never removed entirely — dropping it would join two inline elements that render apart.",
99309943
"multiple": false,
99319944
"simpleType": "boolean",
99329945
},
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases html minimize-collapse-whitespace minimize-collapse-whitespace should compile 1`] = `
4+
"<!doctype html><html lang=en><head><title>Collapse test</title></head><body> <p>Hello <b>world</b> & friends</p> <pre> kept
5+
verbatim</pre> <pre><span>also kept</span></pre> <textarea> kept too </textarea> <p><%= template %></p> <p>one tab</p> <p>already spaced</p> <svg><text>foreign text</text></svg> </body></html>"
6+
`;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigTestCases html minimize-collapse-whitespace minimize-collapse-whitespace should compile 1`] = `
4+
"<!doctype html><html lang=en><head><title>Collapse test</title></head><body> <p>Hello <b>world</b> & friends</p> <pre> kept
5+
verbatim</pre> <pre><span>also kept</span></pre> <textarea> kept too </textarea> <p><%= template %></p> <p>one tab</p> <p>already spaced</p> <svg><text>foreign text</text></svg> </body></html>"
6+
`;

0 commit comments

Comments
 (0)