Skip to content

Commit 7bda3fe

Browse files
feat: safely minify native CSS and HTML via minimizer-webpack-plugin minify functions
1 parent 13c83e6 commit 7bda3fe

25 files changed

Lines changed: 2891 additions & 123 deletions
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+
Safely minify native CSS (with source maps) and HTML output when `optimization.minimize` is enabled.

‎jest.config.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ const config = {
4747
coverageDirectory: "<rootDir>/coverage",
4848
coveragePathIgnorePatterns: [
4949
"\\.runtime\\.js$",
50+
// Serialized to the minimizer's worker pool as source (like runtime code):
51+
// coverage instrumentation would inject counters the worker can't resolve.
52+
"[\\\\/]lib[\\\\/](?:css[\\\\/]cssMinify|html[\\\\/]htmlMinify)\\.js$",
5053
"<rootDir>/test",
5154
"<rootDir>/schemas",
5255
"<rootDir>/examples",

‎lib/config/defaults.js‎

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2400,13 +2400,43 @@ const applyOptimizationDefaults = (
24002400
// Lazy load the minimizer plugin
24012401
const TerserPlugin = require("minimizer-webpack-plugin");
24022402

2403-
new TerserPlugin({
2404-
terserOptions: {
2405-
compress: {
2406-
passes: 2
2407-
}
2408-
}
2409-
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2403+
const terserOptions = { compress: { passes: 2 } };
2404+
2405+
// One minimizer instance (one worker-thread pool) handles JS and, when
2406+
// native CSS / HTML is enabled, those assets too — an array of minify
2407+
// functions each dispatched by its own `filter` (terser -> JS,
2408+
// cssMinify -> CSS, htmlMinify -> HTML). The CSS / HTML serializers stay
2409+
// worker-safe by resolving their parser with `require("webpack/…")` in
2410+
// the worker, so all three share the same pool. `test` is widened to let
2411+
// CSS / HTML assets reach the dispatcher.
2412+
const { css, html } = compiler.options.experiments;
2413+
if (css && html) {
2414+
new TerserPlugin({
2415+
test: /\.(?:[cm]?js|css|html)(\?.*)?$/i,
2416+
minify: [
2417+
TerserPlugin.terserMinify,
2418+
require("../css/cssMinify"),
2419+
require("../html/htmlMinify")
2420+
],
2421+
minimizerOptions: [terserOptions, {}, {}]
2422+
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2423+
} else if (css) {
2424+
new TerserPlugin({
2425+
test: /\.(?:[cm]?js|css)(\?.*)?$/i,
2426+
minify: [TerserPlugin.terserMinify, require("../css/cssMinify")],
2427+
minimizerOptions: [terserOptions, {}]
2428+
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2429+
} else if (html) {
2430+
new TerserPlugin({
2431+
test: /\.(?:[cm]?js|html)(\?.*)?$/i,
2432+
minify: [TerserPlugin.terserMinify, require("../html/htmlMinify")],
2433+
minimizerOptions: [terserOptions, {}]
2434+
}).apply(/** @type {EXPECTED_ANY} */ (compiler));
2435+
} else {
2436+
new TerserPlugin({ terserOptions }).apply(
2437+
/** @type {EXPECTED_ANY} */ (compiler)
2438+
);
2439+
}
24102440
}
24112441
}
24122442
]);

‎lib/css/CssParser.js‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4406,17 +4406,18 @@ class CssParser extends Parser {
44064406
// (per-source) is passed to `process`. One skip set: selector prelude +
44074407
// unread value leaves (non-modules only; CSS Modules needs its selectors
44084408
// and ICSS-captured values).
4409-
new SourceProcessor({
4410-
as: /** @type {"stylesheet" | "block-contents"} */ (this.options.as),
4411-
// Non-modules parses skip selector preludes, but `@custom-selector` expansion needs them, so keep them when the file may use one.
4412-
skip: isModules
4413-
? undefined
4414-
: mayHaveCustomSelectors
4415-
? SKIP_NON_MODULES_KEEP_SELECTORS
4416-
: SKIP_NON_MODULES
4417-
})
4409+
new SourceProcessor()
44184410
.use(/** @type {VisitorMap} */ (visitors))
4419-
.process(source, { locConverter });
4411+
.process(source, {
4412+
as: /** @type {"stylesheet" | "block-contents"} */ (this.options.as),
4413+
// Non-modules parses skip selector preludes, but `@custom-selector` expansion needs them, so keep them when the file may use one.
4414+
skip: isModules
4415+
? undefined
4416+
: mayHaveCustomSelectors
4417+
? SKIP_NON_MODULES_KEEP_SELECTORS
4418+
: SKIP_NON_MODULES,
4419+
locConverter
4420+
});
44204421

44214422
if (customMediaUses || customSelectorUses) resolveCustomMediaAndSelectors();
44224423

‎lib/css/cssMinify.js‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
MIT License http://www.opensource.org/licenses/mit-license.php
3+
Author sheo13666q @sheo13666q
4+
*/
5+
6+
"use strict";
7+
8+
/** @typedef {import("../util/SourceProcessor").SourceMap} SourceMap */
9+
10+
/**
11+
* A `minify` function for `minimizer-webpack-plugin` (passed as its `minify`
12+
* option): safely serializes one CSS asset's minimized form (collapse
13+
* whitespace, drop redundant separators, keep strings / `url(...)` /
14+
* custom-property values verbatim), so CSS minification reuses that plugin's
15+
* pipeline — source maps, caching and worker-thread parallelization.
16+
*
17+
* The parser is read from the public `webpack.css.syntax` API inside the body, not
18+
* imported at module scope: `minimizer-webpack-plugin` ships this function to its
19+
* worker pool as source (a top-level import wouldn't survive), and `require("webpack")`
20+
* re-resolves in the worker — via the installed package, or the dev self-link.
21+
* @param {{ [file: string]: string }} input a single `{ filename: code }` entry
22+
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
23+
* @param {object=} minimizerOptions minimizer options (none used yet)
24+
* @returns {{ code: string, map: SourceMap }} the minified CSS and its input->output source map
25+
*/
26+
const cssMinify = (input, sourceMap, minimizerOptions = {}) => {
27+
// eslint-disable-next-line import/no-extraneous-dependencies -- webpack self-require, re-resolved inside the worker
28+
const webpack = require(/** @type {string} */ ("webpack"));
29+
30+
const { SourceProcessor } = /** @type {typeof import("../index")} */ (webpack)
31+
.css.syntax;
32+
const [[file, code]] = Object.entries(input);
33+
// `process` parses once, and with `minimize` the same walk also prints the
34+
// safely minified serialization — no second parse — and always returns
35+
// `{ code, map }`. `source` / `content` name the map so the plugin can compose
36+
// it back to the original source.
37+
return new SourceProcessor().process(code, {
38+
minimize: true,
39+
source: file,
40+
content: code
41+
});
42+
};
43+
44+
// Worker-safe (see the body's in-worker `require`), so it may run in the shared
45+
// worker-thread pool alongside terser.
46+
cssMinify.supportsWorkerThreads = () => true;
47+
48+
// When several minify functions share one `minimizer-webpack-plugin` instance,
49+
// each asset is dispatched only to the ones whose `filter` accepts it — this
50+
// claims CSS, so terser (JS) and this can coexist in a single plugin / worker pool.
51+
/**
52+
* @param {string} name asset filename
53+
* @returns {boolean} true for CSS assets
54+
*/
55+
cssMinify.filter = (name) => /\.css(\?.*)?$/i.test(name);
56+
57+
module.exports = cssMinify;

0 commit comments

Comments
 (0)