Webpack打包后体积太大,怎么有效压缩JS和CSS?

瑞娜 ☘︎ 阅读 36

我们项目用的是 Webpack 5 + React,最近发现首屏加载特别慢,看了下打包后的 main.js 居然有 2.3MB(未压缩)。我已经开了 mode: 'production',也试过用 TerserPlugin 压缩,但效果不明显。

想问问有没有更有效的体积压缩方案?比如是不是该拆分 vendor 包,或者动态 import 没配对?另外 CSS 是通过 mini-css-extract-plugin 抽出来的,但也没自动压缩,是不是漏了什么插件?

optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\/]node_modules[\/]/,
        name: 'vendors',
        chunks: 'all',
      }
    }
  }
}
我来解答 赞 9 收藏
二维码
手机扫码查看
2 条解答
Prog.希玲
2.3MB确实有点离谱,先看下你TerserPlugin怎么配的,光开production mode压缩力度不够,得手动配一下:

// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 去掉console.log
drop_debugger: true,
pure_funcs: ['console.log'], // 去掉指定函数
},
mangle: true,
output: {
comments: false,
},
},
extractComments: false,
}),
new CssMinimizerPlugin(), // 你说CSS没压缩,就是缺这个
],
},
};


CSS压缩漏了 css-minimizer-webpack-plugin,装一下:

npm install css-minimizer-webpack-plugin -D


然后你那个splitChunks配置有点问题,name写成固定的值会导致缓存失效,改成函数形式:

optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[/]node_modules[/]/,
name(module) {
const packageName = module.context.match(/[/]node_modules[/](.*?)([/]|$)/)[1];
return vendor.${packageName.replace('@', '')};
},
priority: 10,
},
common: {
minChunks: 2,
priority: 5,
reuseExistingChunk: true,
},
},
},
}


这样能把node_modules里的大库拆成单独的chunk,比如react、lodash这些不会全打成一个vendors.js。

动态导入这块,检查下代码里有没有这样写:

// 改成
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

// 路由层面
const Dashboard = React.lazy(() => import('./pages/Dashboard'));


还有几个能显著减小体积的点:

1. 检查是否引入了moment这种大库,换成dayjs或date-fns
2. 检查lodash是不是全量引入,得用lodash-es + babel-plugin-import
3. 图片资源有没有用webpack-asset模块加载

最后跑一下 webpack --profile --json > stats.json,然后用webpack-bundle-analyzer看看到底是哪个模块占空间最大。

基本上就是这些,配完应该能降到几百KB以内。
点赞
2026-03-12 07:01
司空慧娜
别瞎猜,先用 webpack-bundle-analyzer 看看到底是谁在占空间,不然改半天没用。CSS 没压是因为 Webpack 5 把内置的 CSS 压缩去掉了,得自己加 CssMinimizerPlugin。JS 的话,生产模式默认就有 Terser,如果还是大,服务器上开 gzip 比死磕构建压缩效果更明显,省事。

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
plugins: [
// 先看看是谁在占体积,分析完记得把这个插件删掉
new BundleAnalyzerPlugin(),
// CSS 压缩
new CssMinimizerPlugin(),
// 开启 gzip,服务器传输时能省一半流量
new CompressionPlugin({
algorithm: 'gzip',
test: /.(js|css)$/,
threshold: 10240,
}),
],
optimization: {
minimize: true,
minimizer: [
..., // 这三个点必须加,保留 webpack 默认的 js 压缩配置
new CssMinimizerPlugin(),
],
},
};
点赞 1
2026-03-03 23:00