Skip to content

Commit 281c581

Browse files
committed
feat(html): minify the document an <iframe srcdoc> holds
Adds `optimization.minimize.html.minifySrcdoc`, off by default. The body is a whole document of its own, so like a conditional comment's it cannot be minified where it is found: the values are recorded, minified, and put back into the source, which is then minified as usual. A nested iframe recurses.
1 parent d51c2c1 commit 281c581

14 files changed

Lines changed: 211 additions & 5 deletions

File tree

‎.changeset/048-html-remove-redundant-attributes.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-
Minify HTML further: leave out the implied `<html>` tag and any optional end tag nothing prints behind, print an empty attribute value bare, write an attribute value in the fewest bytes that parse back the same, drop an empty attribute and a run of nested empty elements, fold an enumerated value to lower case, and add the `optimization.minimize.html` options `collapseWhitespace`, `mergeStyles`, `minifyConditionalComments`, `preserveComments`, `removeEmptyAttributes`, `removeEmptyElements`, `removeImpliedTags`, `removeRedundantAttributes`, `sortAttributes` and `sortTokenLists`.
5+
Minify HTML further: leave out the implied `<html>` tag and any optional end tag nothing prints behind, print an empty attribute value bare, write an attribute value in the fewest bytes that parse back the same, drop an empty attribute and a run of nested empty elements, fold an enumerated value to lower case, and add the `optimization.minimize.html` options `collapseWhitespace`, `mergeStyles`, `minifyConditionalComments`, `minifySrcdoc` (minify the document an `<iframe srcdoc>` holds), `preserveComments`, `removeEmptyAttributes`, `removeEmptyElements`, `removeImpliedTags`, `removeRedundantAttributes`, `sortAttributes` and `sortTokenLists`.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2422,6 +2422,11 @@ export interface OptimizationMinimizeHtml {
24222422
* @since 5.110.0
24232423
*/
24242424
minifyConditionalComments?: boolean;
2425+
/**
2426+
* 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.
2427+
* @since 5.110.0
2428+
*/
2429+
minifySrcdoc?: boolean;
24252430
/**
24262431
* 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.
24272432
* @since 5.110.0

‎lib/html/htmlMinify.js‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
* re-resolves in the worker — via the installed package, or the dev self-link.
2424
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
2525
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
26-
* @param {HtmlPrintOptions & { minifyConditionalComments?: boolean }=} minimizerOptions minimizer options — `environment` and `convertLengthUnits` reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`
26+
* @param {HtmlPrintOptions & { minifyConditionalComments?: boolean, minifySrcdoc?: boolean }=} minimizerOptions minimizer options — `environment` and `convertLengthUnits` reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`
2727
* @returns {{ code: string }} the minified HTML
2828
*/
2929
const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
@@ -40,7 +40,8 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
4040
// parses but change the attribute string a script reads back, so a consumer
4141
// that compares those bytes wants a way to turn each off. Room to widen them
4242
// too: any boolean value rather than only the canonical spellings.
43-
const { SourceProcessor, NodeType } = webpack.html.syntax;
43+
const { SourceProcessor, NodeType, decodeEntities, escapeAttribute } =
44+
webpack.html.syntax;
4445
const [[, code]] = Object.entries(input);
4546
// The nested CSS minifier gets the abilities and options a `.css` asset
4647
// gets, or the inline copy of a declaration would disagree with it.
@@ -54,6 +55,7 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
5455
preserveComments,
5556
removeRedundantAttributes,
5657
minifyConditionalComments,
58+
minifySrcdoc,
5759
sortAttributes,
5860
sortTokenLists,
5961
removeImpliedTags
@@ -74,6 +76,48 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
7476
sortTokenLists,
7577
removeImpliedTags
7678
};
79+
// An `<iframe srcdoc>` holds a whole document, and like the conditional
80+
// comments below it cannot be minified where it is found. It is put back into
81+
// the source rather than into the output, because the printer respells an
82+
// attribute value — the recorded text is not what the output ends up holding.
83+
// Only a document that names the attribute at all pays the extra parse.
84+
//
85+
// Recursion goes through this local name, never the module's own: the plugin
86+
// ships this function to its workers as source, where that binding is absent.
87+
/**
88+
* @param {string} text markup that may hold `<iframe srcdoc>` documents
89+
* @returns {string} the same markup, each of those minified in place
90+
*/
91+
const minifySrcdocIn = (text) => {
92+
if (!/srcdoc/i.test(text)) return text;
93+
/** @type {{ start: number, end: number, value: string }[]} */
94+
const found = [];
95+
new SourceProcessor()
96+
.use({
97+
[NodeType.Element]: (path) => {
98+
if (path.tagName() !== "iframe") return;
99+
for (const attribute of path.attributes()) {
100+
if (attribute.name !== "srcdoc" || attribute.value === "") continue;
101+
found.push({
102+
start: attribute.valueStart,
103+
end: attribute.valueEnd,
104+
value: attribute.value
105+
});
106+
}
107+
}
108+
})
109+
.process(text, {});
110+
let out = text;
111+
// Back to front, so an earlier splice does not move a later range.
112+
for (let i = found.length - 1; i >= 0; i--) {
113+
const { start, end, value } = found[i];
114+
const body = minifySrcdocIn(decodeEntities(value, true));
115+
const { code: inner } = new SourceProcessor().process(body, printOptions);
116+
out = `${out.slice(0, start)}${escapeAttribute(inner, text.charCodeAt(start - 1), true)}${out.slice(end)}`;
117+
}
118+
return out;
119+
};
120+
const source = minifySrcdoc ? minifySrcdocIn(code) : code;
77121
// A downlevel-hidden conditional comment holds markup, and it cannot be
78122
// minified where it is found: the visitor that finds it runs inside the
79123
// document's own parse, and the walk state is module-scoped, so `grammar`
@@ -106,7 +150,7 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
106150
// `process` parses once, and with `mode: "minify"` its walk also prints the
107151
// safely minified serialization — no second parse. No `source` is named, so no
108152
// map is built: the HTML serialize is token-coarse and only the code is used.
109-
const { code: out } = processor.process(code, printOptions);
153+
const { code: out } = processor.process(source, printOptions);
110154
recording = false;
111155
if (conditionals.size === 0) return { code: out };
112156
let spliced = out;

‎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
@@ -3781,6 +3781,11 @@
37813781
"type": "boolean",
37823782
"added": "5.110.0"
37833783
},
3784+
"minifySrcdoc": {
3785+
"description": "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.",
3786+
"type": "boolean",
3787+
"added": "5.110.0"
3788+
},
37843789
"preserveComments": {
37853790
"description": "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.",
37863791
"type": "array",

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10076,6 +10076,19 @@ Object {
1007610076
"multiple": false,
1007710077
"simpleType": "boolean",
1007810078
},
10079+
"optimization-minimize-html-minify-srcdoc": Object {
10080+
"configs": Array [
10081+
Object {
10082+
"description": "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.",
10083+
"multiple": false,
10084+
"path": "optimization.minimize.html.minifySrcdoc",
10085+
"type": "boolean",
10086+
},
10087+
],
10088+
"description": "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.",
10089+
"multiple": false,
10090+
"simpleType": "boolean",
10091+
},
1007910092
"optimization-minimize-html-preserve-comments": Object {
1008010093
"configs": Array [
1008110094
Object {
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigCacheTestCases html minimize-srcdoc minimize-srcdoc should compile 1`] = `
4+
"<!doctype html><head><title>Srcdoc</title></head><body>
5+
<iframe id=basic srcdoc=\\"<p class=a>hi\\"></iframe>
6+
<iframe id=single srcdoc='<b>bold</b>'></iframe>
7+
<iframe id=nested srcdoc='<iframe srcdoc=\\"<i>deep</i>\\"></iframe>'></iframe>
8+
<iframe id=style srcdoc=\\"<style>.a{color:red}</style><p class=a>styled\\"></iframe>
9+
<iframe id=doctype srcdoc=\\"<!doctype html><body><p>whole</body></html>\\"></iframe>
10+
<iframe id=entities srcdoc=\\"<p>a & b &amp;lt; c\\"></iframe>
11+
<iframe id=quote-in-body srcdoc=\\"<p title=q>quoted\\"></iframe>
12+
<iframe id=upper srcdoc=\\"<em>up</em>\\"></iframe>
13+
<iframe id=empty srcdoc></iframe>
14+
<iframe id=none src=child.html></iframe>
15+
<p>the word srcdoc in text is not an attribute</p>
16+
17+
18+
</body></html>"
19+
`;
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`ConfigTestCases html minimize-srcdoc minimize-srcdoc should compile 1`] = `
4+
"<!doctype html><head><title>Srcdoc</title></head><body>
5+
<iframe id=basic srcdoc=\\"<p class=a>hi\\"></iframe>
6+
<iframe id=single srcdoc='<b>bold</b>'></iframe>
7+
<iframe id=nested srcdoc='<iframe srcdoc=\\"<i>deep</i>\\"></iframe>'></iframe>
8+
<iframe id=style srcdoc=\\"<style>.a{color:red}</style><p class=a>styled\\"></iframe>
9+
<iframe id=doctype srcdoc=\\"<!doctype html><body><p>whole</body></html>\\"></iframe>
10+
<iframe id=entities srcdoc=\\"<p>a & b &amp;lt; c\\"></iframe>
11+
<iframe id=quote-in-body srcdoc=\\"<p title=q>quoted\\"></iframe>
12+
<iframe id=upper srcdoc=\\"<em>up</em>\\"></iframe>
13+
<iframe id=empty srcdoc></iframe>
14+
<iframe id=none src=child.html></iframe>
15+
<p>the word srcdoc in text is not an attribute</p>
16+
17+
18+
</body></html>"
19+
`;
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing
2+
3+
exports[`errors 1`] = `
4+
Array [
5+
"page.html from Terser plugin
6+
htmlMinify is not defined
7+
ReferenceError: htmlMinify is not defined",
8+
]
9+
`;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import "./page.html";
2+
3+
it("should minify the document held in an <iframe srcdoc>", () => {
4+
// The emitted page is the assertion — see the snapshot in test.config.js.
5+
expect(true).toBe(true);
6+
});

0 commit comments

Comments
 (0)