Skip to content

Commit 9cb49ef

Browse files
refactor(html): minify inline CSS and JSON through renderEmbeddedSource alone (#21993)
* refactor(html): route every embedded body through one renderer The printer called its own CSS and JSON minifiers directly at each site, beside the caller's renderer. They are now one built-in renderer of the same shape, asked wherever the caller passed none or declined, so every site makes the same call and adding a language means adding one branch. Output is unchanged. * refactor(html): minify inline CSS and JSON through renderEmbeddedSource alone The HTML printer no longer runs a CSS or JSON minifier of its own: every nested body is offered to `renderEmbeddedSource`, and a body the renderer declines is left as written. `builtinEmbeddedRenderer` exports webpack's own CSS and JSON minifiers as such a renderer; `htmlMinify` composes it behind the caller's, so a custom minimizer answers for the languages it claims and webpack's own answers for the rest. * test(css): decline the languages the embedded svg case does not render Its renderer answered every language with the source unchanged, which under the renderer-only path claims those bodies and leaves a `style=""` as written. Declining them is what a renderer does for a language it does not handle, and puts the case's generated code back to the byte. * test(html): cover the shapes a sheet does not end cleanly in The scan that decides whether a `<style>` run may absorb the next sheet reads escapes, comments and strings, and none of those branches had a test: a build never reaches them, since a sheet a document embeds is normally well formed. * refactor(html): move webpack's own embedded renderer out of the printer The printer ran no CSS through it any more, but still held the code that did: `builtinEmbeddedRenderer` reached for the CSS `SourceProcessor` from `lib/html/syntax.js`. It and `stripJsonWhitespace` move to a module of their own, so the printer file names no minifier but the HTML one, and `html.syntax` re-exports both where callers already look. Its remaining use of the CSS module is the lexer `parseCssUrls` reads `url()` with. * docs(html): cut the JSON stripper's description to two sentences
1 parent a12775b commit 9cb49ef

10 files changed

Lines changed: 437 additions & 386 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+
Minify inline CSS and JSON via `renderEmbeddedSource`, exporting webpack's own.
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author Alexander Akait @alexander-akait
4+
*/
5+
6+
"use strict";
7+
8+
const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
9+
10+
/** @import { CssProcessOptions } from "../css/syntax" */
11+
/** @import { EmbeddedSourceRenderer } from "./syntax" */
12+
13+
/**
14+
* What this minifies inline CSS with: the CSS minifier's own options, so an
15+
* inline declaration is held to the rules a `.css` asset is.
16+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "rewriteCustomProperties" | "transforms" | "unusedSymbols" | "pseudoClasses">} BuiltinEmbeddedRendererOptions
17+
*/
18+
19+
// Both are loaded on first render rather than at module load: a document that
20+
// embeds no CSS and no JSON pays for neither.
21+
/** @type {typeof import("../css/syntax") | undefined} */
22+
let _cssSyntax;
23+
/** @type {typeof import("./syntax") | undefined} */
24+
let _htmlSyntax;
25+
26+
/**
27+
* Strip the whitespace between a JSON body's tokens, every literal copied byte
28+
* for byte. Re-serializing would round numbers, drop a duplicate key and rewrite
29+
* the escapes that keep a string from closing the `<script>` early.
30+
* @param {string} json a `<script>` body
31+
* @returns {string} the stripped body, or the body as written where it is not JSON
32+
*/
33+
const stripJsonWhitespace = (json) => {
34+
try {
35+
JSON.parse(json);
36+
} catch (_err) {
37+
// Not JSON after all (a template, a placeholder) — not ours to touch.
38+
return json;
39+
}
40+
let out = "";
41+
let inString = false;
42+
let escaped = false;
43+
for (let i = 0; i < json.length; i++) {
44+
const c = json.charCodeAt(i);
45+
if (inString) {
46+
out += json[i];
47+
if (escaped) escaped = false;
48+
else if (c === 0x5c) escaped = true;
49+
else if (c === 0x22) inString = false;
50+
continue;
51+
}
52+
if (c === 0x22) {
53+
inString = true;
54+
out += json[i];
55+
continue;
56+
}
57+
// JSON whitespace (RFC 8259): tab, LF, CR, space.
58+
if (c === 0x09 || c === 0x0a || c === 0x0d || c === 0x20) continue;
59+
out += json[i];
60+
}
61+
return out;
62+
};
63+
64+
/**
65+
* The renderer webpack ships for what a document embeds: its own CSS minifier
66+
* for a `<style>` or `style=""` and `stripJsonWhitespace` for JSON, declining
67+
* every other language. A caller passes it where it has no renderer of its own,
68+
* or behind one for the languages that one declines — the HTML printer minifies
69+
* none of this itself.
70+
* @param {BuiltinEmbeddedRendererOptions=} options the CSS minifier's options, so an inline declaration is minified as the `.css` assets are
71+
* @returns {EmbeddedSourceRenderer} the renderer
72+
*/
73+
const builtinEmbeddedRenderer = (options = {}) => {
74+
const { BLOCK_CONTENTS, JSON_TYPE } =
75+
_htmlSyntax || (_htmlSyntax = require("./syntax"));
76+
const sheet = { mode: /** @type {"minify"} */ ("minify"), ...options };
77+
const block = { ...sheet, as: BLOCK_CONTENTS };
78+
// A `style=""` repeats across a document far more often than it varies.
79+
/** @type {Map<string, string>} */
80+
const blocks = new Map();
81+
return (source, info) => {
82+
if (info.type === JSON_TYPE) return stripJsonWhitespace(source);
83+
if (info.type !== CSS_TYPE) return undefined;
84+
const isBlock = info.as === BLOCK_CONTENTS;
85+
if (isBlock) {
86+
const memoized = blocks.get(source);
87+
if (memoized !== undefined) return memoized;
88+
}
89+
const { SourceProcessor } =
90+
_cssSyntax || (_cssSyntax = require("../css/syntax"));
91+
let code;
92+
try {
93+
code = new SourceProcessor().process(
94+
source,
95+
isBlock ? block : sheet
96+
).code;
97+
} catch (_err) {
98+
// Text the minifier cannot read is left as written, by declining.
99+
return undefined;
100+
}
101+
if (isBlock) blocks.set(source, code);
102+
return code;
103+
};
104+
};
105+
106+
module.exports.builtinEmbeddedRenderer = builtinEmbeddedRenderer;
107+
module.exports.stripJsonWhitespace = stripJsonWhitespace;

‎lib/html/htmlMinify.js‎

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

88
/** @import { DeferredEmbeddedSource, HtmlPrintOptions } from "../html/syntax" */
9+
/** @import { CssEnvironment } from "../css/syntax" */
910

1011
/**
1112
* What a renderer made of one embedded body: the minified text, and anything it
@@ -34,7 +35,7 @@
3435
* re-resolves in the worker — via the installed package, or the dev self-link.
3536
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3637
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
37-
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { 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, 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
3839
* @returns {Promise<{ code: string, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified HTML, and what a renderer reported over what it embeds
3940
*/
4041
const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -47,6 +48,7 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
4748
// value the spec does not name.
4849
const {
4950
askEmbeddedRenderer,
51+
builtinEmbeddedRenderer,
5052
collectEmbeddedDiagnostics,
5153
embeddedText,
5254
SourceProcessor,
@@ -78,17 +80,20 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
7880
// the top rather than lost at the level that heard it.
7981
/** @type {EmbeddedSourceResult[]} */
8082
const reported = [];
83+
// Webpack's own renderer, handed the CSS minifier's options so an inline
84+
// declaration agrees with the `.css` asset; each language picks its switches.
85+
const builtin = builtinEmbeddedRenderer({
86+
environment,
87+
convertLengthUnits: css.convertLengthUnits,
88+
rewriteCustomProperties: css.rewriteCustomProperties,
89+
unusedSymbols: css.unusedSymbols,
90+
pseudoClasses: css.pseudoClasses,
91+
transforms: webpack.css.syntax.pickTransforms(css)
92+
});
8193
// One set of options, handed to the document pass and to each conditional
8294
// comment's body below.
8395
const printOptions = {
8496
mode: /** @type {"minify"} */ ("minify"),
85-
environment,
86-
convertLengthUnits: css.convertLengthUnits,
87-
rewriteCustomProperties: css.rewriteCustomProperties,
88-
cssUnusedSymbols: css.unusedSymbols,
89-
cssPseudoClasses: css.pseudoClasses,
90-
// Each language picks its own switches out of its own options object.
91-
cssTransforms: webpack.css.syntax.pickTransforms(css),
9297
transforms: pickTransforms(minimizerOptions),
9398
collapseWhitespace,
9499
mergeStyles,
@@ -117,8 +122,10 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
117122
if (typeof answered === "string") return answered;
118123
}
119124

120-
// A nested document is a document, so it is minified the same way. The
121-
// built-in CSS and JSON minifiers already reach every other body.
125+
// Webpack's own answers for what the caller's left: CSS and JSON, and a
126+
// nested document, which is a document minified the same way.
127+
const own = builtin(source, hole);
128+
if (own !== undefined) return own;
122129
return hole.type === "html" ? minifyDocument(source) : undefined;
123130
};
124131
/**
@@ -217,9 +224,7 @@ htmlMinify.getTypes = () => ["html"];
217224
* The languages this can offer a caller through `renderEmbeddedSource` — an
218225
* inline `<style>`, a `<script>`, every event handler attribute (as the
219226
* function body it is), an `<svg>` subtree and the document an
220-
* `<iframe srcdoc>` holds. A `style=""` is not among them: how the attribute is
221-
* written is decided by reading the minified text back, so it stays with the
222-
* built-in CSS minifier, which is webpack's own `cssMinify`.
227+
* `<iframe srcdoc>` holds, and every `style=""` as the block's contents it is.
223228
* @returns {string[]} the languages
224229
*/
225230
htmlMinify.getEmbeddedTypes = () => {

0 commit comments

Comments
 (0)