Skip to content

Commit 5a8fa6c

Browse files
feat: configure or exclude each asset type's minifier via optimization.minimize (#21663)
* feat: configure or exclude each asset type's minifier via optimization.minimize `optimization.minimize` also accepts an object keyed by asset type (`javascript`, `css`, `html`): `false` excludes a type from the built-in minimizer, an object configures what it may do beyond the always-applied transforms. First option: `css.convertLengthUnits`, handed to `.css` assets and the inline CSS in HTML alike. * feat: normalize optimization.minimize and hand JS minimizer options through it Per-type values are `false | options` — enable-with-defaults is expressed by omitting the key, like `splitChunks`. Normalization canonicalizes the `true` shorthand into the object form, and the defaults fill each type, so the JS minimizer's `{ compress: { passes: 2 } }` shows up in the resolved config and is overridable (`minimize.javascript` is handed as-is to the minimizer). * style: tighten comments to the two-line limit and use precise minimizer option types * feat(html): add optimization.minimize.html.collapseWhitespace The first HTML-specific minimizer option, wired through the per-type map: each run of text whitespace collapses to one space — never removed outright — skipping `pre` / `textarea` / `listing` ancestors and any text carrying a `<`, which stays on the source-passthrough path. * style: trim collapse-whitespace comments and stabilize formatting Prettier's first pass over two untouched regions was not a fixed point; the committed form now matches what `--check` verifies. * test(html): drive collapseWhitespace through SourceProcessor in-process The config case exercises it only inside the minimizer's worker pool, which jest's coverage cannot see — the same reason the CSS `convertLengthUnits` transforms are unit-tested directly.
1 parent 78d0d4c commit 5a8fa6c

53 files changed

Lines changed: 1115 additions & 64 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
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+
Configure or exclude each asset type's minifier via `optimization.minimize`.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2270,9 +2270,9 @@ 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 the built-in minimizer per asset type.
22742274
*/
2275-
minimize?: boolean;
2275+
minimize?: boolean | OptimizationMinimizeOptions;
22762276
/**
22772277
* Minimizer(s) to use for minimizing the output.
22782278
*/
@@ -2337,6 +2337,53 @@ export interface ConcatenateModulesOptions {
23372337
*/
23382338
commonjs?: boolean;
23392339
}
2340+
/**
2341+
* Enable minimizing the output, configured per asset type. An absent type is minimized with the defaults; `false` disables minimizing it.
2342+
* @since 5.110.0
2343+
*/
2344+
export interface OptimizationMinimizeOptions {
2345+
/**
2346+
* Minimize CSS assets: `false` disables it, an object configures what the built-in minimizer may do beyond the transforms that always apply.
2347+
*/
2348+
css?: false | OptimizationMinimizeCss;
2349+
/**
2350+
* Minimize HTML assets: `false` disables it, an object configures what the built-in minimizer may do beyond the transforms that always apply.
2351+
*/
2352+
html?: false | OptimizationMinimizeHtml;
2353+
/**
2354+
* Minimize JavaScript assets: `false` disables it, an object is handed as-is to the JavaScript minimizer.
2355+
*/
2356+
javascript?: false | OptimizationMinimizeJavascript;
2357+
}
2358+
/**
2359+
* What the CSS minimizer may do beyond the transforms that always apply. Applies wherever it runs: on `.css` assets and on the inline `<style>` / `style=""` the HTML minimizer hands it.
2360+
* @since 5.110.0
2361+
*/
2362+
export interface OptimizationMinimizeCss {
2363+
/**
2364+
* Rewrite a length into a shorter unit it is exactly equal in (`16px` -> `1pc`). Off by default: the authored unit is lost, and once the asset is compressed the rewrite rarely earns anything.
2365+
* @since 5.110.0
2366+
*/
2367+
convertLengthUnits?: boolean;
2368+
}
2369+
/**
2370+
* What the HTML minimizer may do beyond the transforms that always apply.
2371+
* @since 5.110.0
2372+
*/
2373+
export interface OptimizationMinimizeHtml {
2374+
/**
2375+
* Collapse each run of whitespace in text to a single space. Left alone inside `pre`, `textarea` and `listing`, where whitespace renders verbatim, and never removed entirely — dropping it would join two inline elements that render apart.
2376+
* @since 5.110.0
2377+
*/
2378+
collapseWhitespace?: boolean;
2379+
}
2380+
/**
2381+
* Options handed as-is to the JavaScript minimizer (terser-compatible). Defaults to `{ compress: { passes: 2 } }`.
2382+
* @since 5.110.0
2383+
*/
2384+
export interface OptimizationMinimizeJavascript {
2385+
[k: string]: any;
2386+
}
23402387
/**
23412388
* Plugin instance.
23422389
*/
@@ -4429,9 +4476,9 @@ export interface OptimizationNormalized {
44294476
*/
44304477
mergeDuplicateChunks?: boolean;
44314478
/**
4432-
* Enable minimizing the output. Uses optimization.minimizer.
4479+
* Enable minimizing the output. Uses optimization.minimizer. An object configures the built-in minimizer per asset type.
44334480
*/
4434-
minimize?: boolean;
4481+
minimize?: false | OptimizationMinimizeOptions;
44354482
/**
44364483
* Minimizer(s) to use for minimizing the output.
44374484
*/

‎lib/config/defaults.js‎

Lines changed: 64 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ const {
6666
/** @typedef {import("../../declarations/WebpackOptions").HashDigestLength} HashDigestLength */
6767
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
6868
/** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
69+
/** @typedef {import("../../declarations/WebpackOptions").OptimizationMinimizeOptions} OptimizationMinimizeOptions */
6970
/** @typedef {import("../../declarations/WebpackOptions").OptimizationNormalized} Optimization */
7071
/** @typedef {import("../../declarations/WebpackOptions").OptimizationSplitChunksOptions} OptimizationSplitChunksOptions */
7172
/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
@@ -2087,7 +2088,9 @@ const applyOutputDefaults = (
20872088
"hotUpdateMainFilename",
20882089
// Only `chunkLoading: "import"` loads the manifest via `import()` (needs an
20892090
// `export default` ES module); every other loader fetches it as raw JSON.
2090-
`[runtime].[fullhash].hot-update.${output.chunkLoading === "import" ? "json.mjs" : "json"}`
2091+
`[runtime].[fullhash].hot-update.${
2092+
output.chunkLoading === "import" ? "json.mjs" : "json"
2093+
}`
20912094
);
20922095
D(output, "crossOriginLoading", false);
20932096
F(output, "scriptType", () => (output.module ? "module" : false));
@@ -2428,15 +2431,21 @@ const applyOptimizationDefaults = (
24282431
D(optimization, "mangleWasmImports", false);
24292432
D(optimization, "portableRecords", records);
24302433
D(optimization, "realContentHash", production);
2431-
D(optimization, "minimize", production);
2434+
F(optimization, "minimize", () => (production ? {} : false));
2435+
const { minimize } = optimization;
2436+
if (minimize) {
2437+
// Canonicalize the object form: the JS minimizer's defaults become
2438+
// visible in the resolved config rather than hidden in the wiring.
2439+
F(minimize, "javascript", () => ({ compress: { passes: 2 } }));
2440+
F(minimize, "css", () => ({}));
2441+
F(minimize, "html", () => ({}));
2442+
}
24322443
A(optimization, "minimizer", () => [
24332444
{
24342445
apply: (compiler) => {
24352446
// Lazy load the minimizer plugin
24362447
const TerserPlugin = require("minimizer-webpack-plugin");
24372448

2438-
const terserOptions = { compress: { passes: 2 } };
2439-
24402449
// One minimizer instance (one worker-thread pool) handles JS and, when
24412450
// native CSS / HTML is enabled, those assets too — an array of minify
24422451
// functions each dispatched by its own `filter` (terser -> JS,
@@ -2454,19 +2463,38 @@ const applyOptimizationDefaults = (
24542463
compiler
24552464
);
24562465

2466+
// Normalized + defaulted `optimization.minimize` is the per-asset-type
2467+
// object here: `false` disables a type, an object is its options.
2468+
const minimizeByType = /** @type {OptimizationMinimizeOptions} */ (
2469+
compiler.options.optimization.minimize
2470+
);
2471+
const terserOptions = minimizeByType.javascript || {
2472+
compress: { passes: 2 }
2473+
};
2474+
24572475
const { css, html } = compiler.options.experiments;
2458-
const minifyCss = Boolean(css) && !claimedByOtherMinimizer.css;
2459-
const minifyHtml = Boolean(html) && !claimedByOtherMinimizer.html;
2460-
if (!minifyCss && !minifyHtml) {
2476+
const minifyJs = minimizeByType.javascript !== false;
2477+
const minifyCss =
2478+
Boolean(css) &&
2479+
!claimedByOtherMinimizer.css &&
2480+
minimizeByType.css !== false;
2481+
const minifyHtml =
2482+
Boolean(html) &&
2483+
!claimedByOtherMinimizer.html &&
2484+
minimizeByType.html !== false;
2485+
if (!minifyJs && !minifyCss && !minifyHtml) return;
2486+
if (minifyJs && !minifyCss && !minifyHtml) {
24612487
new TerserPlugin({ terserOptions }).apply(
24622488
/** @type {EXPECTED_ANY} */ (compiler)
24632489
);
24642490
return;
24652491
}
24662492
/** @type {(typeof TerserPlugin.terserMinify | typeof import("../css/cssMinify") | typeof import("../html/htmlMinify"))[]} */
2467-
const minify = [TerserPlugin.terserMinify];
2493+
const minify = [];
24682494
/** @type {EXPECTED_OBJECT[]} */
2469-
const minimizerOptions = [terserOptions];
2495+
const minimizerOptions = [];
2496+
/** @type {string[]} */
2497+
const extensions = [];
24702498
// The spellings the CSS minifier may reach for are the ones the target
24712499
// supports, the way `output.environment` already gates the JS output's.
24722500
// HTML gets the same object: an inline `<style>` or `style=""` runs
@@ -2479,22 +2507,40 @@ const applyOptimizationDefaults = (
24792507
cssInsetShorthand: outputEnvironment.cssInsetShorthand !== false,
24802508
cssMediaQueryRange: outputEnvironment.cssMediaQueryRange !== false
24812509
};
2510+
// `minimize.css` follows the CSS minifier wherever it runs: the HTML
2511+
// entry gets the same options, like the shared environment above.
2512+
const cssOptions =
2513+
typeof minimizeByType.css === "object"
2514+
? minimizeByType.css
2515+
: undefined;
2516+
const htmlOptions =
2517+
typeof minimizeByType.html === "object"
2518+
? minimizeByType.html
2519+
: undefined;
2520+
if (minifyJs) {
2521+
minify.push(TerserPlugin.terserMinify);
2522+
minimizerOptions.push(terserOptions);
2523+
extensions.push("[cm]?js");
2524+
}
24822525
if (minifyCss) {
24832526
minify.push(require("../css/cssMinify"));
2484-
minimizerOptions.push({ environment: cssEnvironment });
2527+
minimizerOptions.push({
2528+
environment: cssEnvironment,
2529+
...cssOptions
2530+
});
2531+
extensions.push("css");
24852532
}
24862533
if (minifyHtml) {
24872534
minify.push(require("../html/htmlMinify"));
2488-
minimizerOptions.push({ environment: cssEnvironment });
2489-
}
2490-
while (minimizerOptions.length < minify.length) {
2491-
minimizerOptions.push({});
2535+
minimizerOptions.push({
2536+
environment: cssEnvironment,
2537+
...cssOptions,
2538+
...htmlOptions
2539+
});
2540+
extensions.push("html");
24922541
}
24932542
new TerserPlugin({
2494-
test: new RegExp(
2495-
`\\.(?:[cm]?js${minifyCss ? "|css" : ""}${minifyHtml ? "|html" : ""})(\\?.*)?$`,
2496-
"i"
2497-
),
2543+
test: new RegExp(`\\.(?:${extensions.join("|")})(\\?.*)?$`, "i"),
24982544
minify,
24992545
minimizerOptions
25002546
}).apply(/** @type {EXPECTED_ANY} */ (compiler));

‎lib/config/normalization.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const util = require("util");
1515
/** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
1616
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
1717
/** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptionsNormalized */
18+
/** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */
1819
/** @typedef {import("../../declarations/WebpackOptions").OptimizationNormalized} OptimizationNormalized */
1920
/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunk} OptimizationRuntimeChunk */
2021
/** @typedef {import("../../declarations/WebpackOptions").OptimizationRuntimeChunkNormalized} OptimizationRuntimeChunkNormalized */
@@ -326,6 +327,7 @@ const getNormalizedWebpackOptions = (config) => ({
326327
cacheGroups: cloneObject(splitChunks.cacheGroups)
327328
}
328329
),
330+
minimize: getNormalizedOptimizationMinimize(optimization.minimize),
329331
minimizer:
330332
optimization.minimizer !== undefined
331333
? /** @type {OptimizationNormalized["minimizer"]} */ (
@@ -604,6 +606,19 @@ const getNormalizedEntryStatic = (entry) => {
604606
return result;
605607
};
606608

609+
/**
610+
* Gets normalized optimization minimize: the `true` shorthand becomes an empty
611+
* per-asset-type object, so downstream only sees `false` or the object form.
612+
* @param {Optimization["minimize"]} minimize minimize option
613+
* @returns {OptimizationNormalized["minimize"]} normalized minimize option
614+
*/
615+
const getNormalizedOptimizationMinimize = (minimize) => {
616+
if (minimize === undefined) return;
617+
if (minimize === false) return false;
618+
if (minimize === true) return {};
619+
return cloneObject(minimize);
620+
};
621+
607622
/**
608623
* Gets normalized optimization runtime chunk.
609624
* @param {OptimizationRuntimeChunk=} runtimeChunk runtimeChunk option

‎lib/css/cssMinify.js‎

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
* re-resolves in the worker — via the installed package, or the dev self-link.
2323
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
2424
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
25-
* @param {object=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for
25+
* @param {{ environment?: CssEnvironment, convertLengthUnits?: boolean }=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`)
2626
* @returns {{ code: string, map: SourceMap }} the minified CSS and its input->output source map
2727
*/
2828
const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
@@ -31,9 +31,8 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
3131
require(/** @type {string} */ ("webpack"))
3232
);
3333

34-
// TODO expose the transforms webpack declines as options, each off by
35-
// default. Every one is something csso, cssnano, lightningcss or esbuild ships
36-
// on, and every one costs something a build may not want to pay:
34+
// TODO expose the remaining declined transforms on `optimization.minimize.css`
35+
// like `convertLengthUnits`. Each is on in other minifiers; what each costs:
3736
// - custom-property rewrites (`--r:0.5rem` -> `.5rem`), observable through
3837
// `getComputedStyle().getPropertyValue()`, the one place a declaration's
3938
// authored text survives;
@@ -44,12 +43,6 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
4443
// it). Adjacent rules sharing a block do join, nothing being between them to
4544
// step over — only where every selector is a shape each engine parses, since
4645
// one it cannot invalidates the whole list and loses the rest with it;
47-
// - rewriting a length into a shorter unit it is exactly equal in
48-
// (`convertLengthUnits`). It is sound — CSS Values 4 fixes the absolute
49-
// units against each other, so `1pc` is `16px` on every medium — but it
50-
// fires ten times in all of Bootstrap and once in a Tailwind build, and
51-
// after gzip it costs as many bytes as it saves. `cssnano` disables the
52-
// same rewrite in its default preset. `ms` <-> `s` is not gated;
5346
// - the color conversions webpack declines rather than guesses. Every polar and
5447
// Lab function converts to hex, except two cases the other minifiers convert
5548
// regardless: a channel landing near a `.5` boundary, where implementations
@@ -78,13 +71,13 @@ const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
7871
// safely minified serialization — no second parse — and always returns
7972
// `{ code, map }`. `source` / `content` name the map so the plugin can compose
8073
// it back to the original source.
74+
const { environment, convertLengthUnits } = minimizerOptions;
8175
return new SourceProcessor().process(code, {
8276
minimize: true,
8377
source: file,
8478
content: code,
85-
environment: /** @type {{ environment?: CssEnvironment }} */ (
86-
minimizerOptions
87-
).environment
79+
environment,
80+
convertLengthUnits
8881
});
8982
};
9083

‎lib/html/htmlMinify.js‎

Lines changed: 8 additions & 8 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 {object=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities, for the inline CSS this minifies
26+
* @param {{ environment?: CssEnvironment, convertLengthUnits?: boolean, collapseWhitespace?: 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 = {}) => {
@@ -52,18 +52,18 @@ const htmlMinify = (input, sourceMap, minimizerOptions = {}) => {
5252
// too: any boolean value rather than only the canonical spellings.
5353
const { SourceProcessor } = webpack.html.syntax;
5454
const [[, code]] = Object.entries(input);
55-
// An inline `<style>` or `style=""` runs through the CSS minifier, so it needs
56-
// the same target abilities a `.css` asset gets — without them the two would
57-
// disagree on a hex alpha, `inset` or a media range.
58-
const { environment } = /** @type {{ environment?: CssEnvironment }} */ (
59-
minimizerOptions
60-
);
55+
// The nested CSS minifier gets the abilities and options a `.css` asset
56+
// gets, or the inline copy of a declaration would disagree with it.
57+
const { environment, convertLengthUnits, collapseWhitespace } =
58+
minimizerOptions;
6159
// `process` parses once, and with `minimize` its walk also prints the safely
6260
// minified serialization — no second parse. It returns `{ code, map }`, but the
6361
// HTML serialize is token-coarse so the map has no mappings; only the code is used.
6462
const { code: out } = new SourceProcessor().process(code, {
6563
minimize: true,
66-
environment
64+
environment,
65+
convertLengthUnits,
66+
collapseWhitespace
6767
});
6868
return { code: out };
6969
};

0 commit comments

Comments
 (0)