1,安装插件
npm install compression-webpack-plugin --save--dev
2,引用插件和配置规则
const CompressionPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
3,在webpack插件中使用
new CompressionPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: productionGzipExtensions,
threshold: 10240,
minRatio: 0.8,
deleteOriginalAssets: false
})
//比如react的webpack配置中
config.plugins.push(
new CompressionPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: productionGzipExtensions,
threshold: 10240,
minRatio: 0.8,
deleteOriginalAssets: false
}),
);
//比如umi配置中
chainWebpack(memo) {
memo.devtool = false;
memo.plugin('CompressionPlugin').use(new CompressionPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: productionGzipExtensions,
// 只处理大于xx字节 的文件,默认:0
threshold: 10240,
// 示例:一个1024b大小的文件,压缩后大小为768b,minRatio : 0.75
minRatio: 0.8, // 默认: 0.8
// 是否删除源文件,默认: false
deleteOriginalAssets: false,
}));
}