1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import CSSMinimizerWebpackPlugin from '../compiled/css-minimizer-webpack-plugin';
import TerserPlugin from '../compiled/terser-webpack-plugin';
import Config from '../compiled/webpack-5-chain';
const ESBuildCSSMinifyPlugin = require('../plugins/ESBuildCSSMinifyPlugin');
// eslint-disable-next-line import/extensions
const ParcelCSSMinifyPlugin = require('../plugins/ParcelCSSMinifyPlugin');
// eslint-disable-next-line import/extensions
const { CSSMinifier, Env, JSMinifier } = require('../types');
const { getEsBuildTarget } = require('../utils/getEsBuildTarget');
async function addCompressPlugin(opts) {
const { config, userConfig, env } = opts;
const jsMinifier = userConfig.jsMinifier || JSMinifier.esbuild;
const cssMinifier = userConfig.cssMinifier || CSSMinifier.esbuild;
if (
env === Env.development ||
process.env.COMPRESS === 'none' ||
(jsMinifier === JSMinifier.none && cssMinifier === CSSMinifier.none)
) {
config.optimization.minimize(false);
return;
}
config.optimization.minimize(true);
let minify: any;
let terserOptions;
if (jsMinifier === JSMinifier.esbuild) {
minify = TerserPlugin.esbuildMinify;
terserOptions = {
target: getEsBuildTarget({
targets: userConfig.targets || {},
}),
};
} else if (jsMinifier === JSMinifier.terser) {
minify = TerserPlugin.terserMinify;
} else if (jsMinifier === JSMinifier.swc) {
minify = TerserPlugin.swcMinify;
} else if (jsMinifier === JSMinifier.uglifyJs) {
minify = TerserPlugin.uglifyJsMinify;
} else if (jsMinifier !== JSMinifier.none) {
throw new Error(`Unsupported jsMinifier ${userConfig.jsMinifier}.`);
}
terserOptions = {
...terserOptions,
...userConfig.jsMinifierOptions,
};
if (jsMinifier !== JSMinifier.none) {
config.optimization.minimizer(`js-${jsMinifier}`).use(TerserPlugin, [
{
minify,
terserOptions,
},
]);
}
if (cssMinifier === CSSMinifier.esbuild) {
config.optimization.minimizer(`css-${cssMinifier}`).use(ESBuildCSSMinifyPlugin, [userConfig.cssMinifierOptions]);
} else if (cssMinifier === CSSMinifier.cssnano) {
config.optimization.minimizer(`css-${cssMinifier}`).use(CSSMinimizerWebpackPlugin, [
{
minimizerOptions: userConfig.cssMinifierOptions,
parallel: true,
},
]);
} else if (cssMinifier === CSSMinifier.parcelCSS) {
config.optimization.minimizer(`css-${cssMinifier}`).use(ParcelCSSMinifyPlugin);
} else if (cssMinifier !== CSSMinifier.none) {
throw new Error(`Unsupported cssMinifier ${userConfig.cssMinifier}.`);
}
}
module.exports = addCompressPlugin;