1.安装CompressionWebpackPlugin
命令:npm i -D compression-webpack-plugin
2.引入以下代码
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩, 按需写入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
configureWebpack: config => {
// 开启 gzip 压缩
const plugins = [];
if (IS_PROD) {
plugins.push(
new CompressionWebpackPlugin({
filename: "[path].gz[query]",
algorithm: "gzip",
test: productionGzipExtensions,
threshold: 10240,
minRatio: 0.8
})
);
}
config.plugins = [...config.plugins, ...plugins];
}
安装cnpm install -d --save image-webpack-loader
chainWebpack: config => {
config.module
.rule('min-image')
.test(/\.(png|jpe?g|gif)(\?.*)?$/)
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({disable: process.env.NODE_ENV == 'development' ? true : false})//此处为ture的时候不会启用压缩处理,目的是为了开发模式下调试速度更快,网上错误示例直接写为disable:true,如果不去查看文档肯定是要被坑的
.end()
// 打包分析
// 打包之后自动生成一个名叫report.html文件(可忽视)
if (IS_PROD) {
config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
{
analyzerMode: "static"
}
]);
}
},
如果报错 Cannot read property ‘tapPromise‘ of undefined
cnpm i -D compression-webpack-plugin@6.1.1