webpack打包生成gz文件
安装插件(compression-webpack-plugin):
npm install compression-webpack-plugin --save-dev
vue.config.js文件进行webpack配置(没有此文件可以在项目根路径创建一个文件):
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
plugins: [
new CompressionPlugin({
algorithm: 'gzip', // 使用gzip压缩
test: /\.js$|\.html$|\.css$/, // 匹配文件名
//filename: '[path].gz[query]', // 压缩后的文件名(保持原文件名,后缀加.gz)
minRatio: 1, // 压缩率小于1才会压缩
threshold: 10240, // 对超过10k的数据压缩
deleteOriginalAssets: false, // 是否删除未压缩的源文件,谨慎设置,如果希望提供非gzip的资源,可不设置或者设置为false(比如删除打包后的gz后还可以加载到原始资源文件)
}),
],
},
};
常见问题
Invalid options in vue.config.js: "plugins" is not allowed
一开始我将plugins直接放在外边,没加configureWebpack,就报了下面的错,参考了链接,加了configureWebpack就ok啦
var webpack=require('webpack')
const path = require('path');
function resolve (dir) {
return path.join(__dirname, dir)
}
module.exports = {
chainWebpack: config => {
//路径配置
config.resolve.alias
.set('assets', resolve('src/assets'))
.set('styles', resolve('src/assets/styles'))
},
// webpack-dev-server 相关配置
devServer: {
// 调试端口
// port: 8989
},
//其他配置....
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"windows.jQuery": "jquery"
})
]
}
}
解决 TypeError: Cannot read property ‘tapPromise‘ of undefined
在使用 compression-webpack-plugin 插件时报这个错误,原因是版本问题。
ERROR TypeError: Cannot read property 'tapPromise' of undefined
TypeError: Cannot read property 'tapPromise' of undefined
安装插件的时候默认最新版本,但是可能脚手架还不支持这个版本,所以需要降低插件版本进行使用,这边在安装的时候最新版本为 v9.2.0,降到 v6.1.1 进行使用
$ npm install [email protected]
然后重新打包正常!