Gzip压缩
- 安装 npm install compression-webpack-plugin -D
注意:不要安装最新版本,否则容易build失败,报错类似在xx.js中 ** undefined或者 TypeEror之类的,都考虑当前包版本与其他包存在兼容性问题。
2.配置 在vue.config.js中配置
// gzip --start
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzip = true // 是否使用gzip
const productionGzipExtensions = ['js', 'css'] // 需要gzip压缩的文件后缀
// gzip --end
//将此配置写在module.exports{ configureWebpack对象里 }
configureWebpack: config => {
const myConfig = {}
if (process.env.NODE_ENV === 'production') {
// 1. 生产环境npm包转CDN
myConfig.externals = externals
myConfig.plugins = []
// gzip
// 2. 构建时开启gzip,降低服务器压缩对CPU资源的占用,服务器也要相应开启gzip
productionGzip && myConfig.plugins.push(
new CompressionWebpackPlugin({
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 100,
minRatio: 0.8
})
)
// 去掉注释
myConfig.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false, // 去掉注释
},
compress: {
drop_console: true,
drop_debugger: false,
pure_funcs: ['console.log'],//移除console
properties:true
// dead_code:true
},
sourceMap: true
}
})
)
}
return myConfig
}
3.执行npm run build 查看输出目录下js和和css是否有压缩文件生成
4.前端没问题了,开始配置服务器也支持gzip,具体参照
vue 项目首屏加载性能调优 第4条
uglifyjs 压缩取消注释
官方有提醒,uglifyjs不支持es6语法,需要支持es6可用terser替换。
功能:压缩js,生产环境下注释掉console.log
- 下载包 npm install uglifyjs-webpack-plugin -D
- vue.config.js配置
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
//将此配置写在module.exports{ configureWebpack对象里 } 最后记得return
// 去掉注释
myConfig.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: false, // 去掉注释
},
compress: {
drop_console: true,
drop_debugger: false,
pure_funcs: ['console.log'],//移除console
properties:true
// dead_code:true
}
},
sourceMap: true
})
)
- npm run build一下,看是否报错。参考博文
terser(uglifyjs的升级版)
参考博文
使用terser-webpack-plugin (npm i terser-webpack-plugin)
因为uglifyjs不支持es6语法,所以用terser-webpack-plugin替代uglifyjs-webpack-plugin
terser-webpack-plugin 目前最新的版本打包会有兼容问题请使用4.2.3版本(20201130)
terser-webpack-plugin的5.x版本是对应webpack5.x所以如果打包失败注意下版本哦
//压缩代码并去掉console es6
const TerserPlugin = require('terser-webpack-plugin')
configureWebpack: (config) => {
let optimization = {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
},
// 具体代码
minimize: true,
minimizer: [new TerserPlugin({
parallel: true,
sourceMap: true,
terserOptions: {
warnings: false,
compress: {
drop_console: true,// 注释console
drop_debugger: true, // 注释debugger
pure_funcs: ["console.log"]
}
}
})]
};
Object.assign(config, {
optimization,
// 插件配置
plugins:[
...config.plugins
]
})
}
总结:对某项配置不明白的,搜官网看解释,或者搜对应的中文网看解释!熟能生巧