一、配置 gzip 压缩,打出来一个待 gzip 后缀的文件
我安装的6.0.0版本,版本过高打包的时候会报有什么东西找不到。。。
npm i compression-webpack-plugin -D
vue.config.js
const CompressionWebpackPlugin = require('compression-webpack-plugin')
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
...[
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: /\.(js|css|html|svg)$/i,
threshold: 2048,
minRatio: 0.8
})
]
)
}
}
}
二、uglifyjs-webpack-plugin 代码打包与压缩(亲测简单有效)
打包前 895kb
打包后 153kb
$ npm install uglifyjs-webpack-plugin --save-de
vue.config.js
isProduction是环境判断,本代码使用了但未定义
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
configureWebpack: config => {
// 生产环境相关配置
if (isProduction == "production") {
// 代码压缩
config.plugins.push(
new UglifyJsPlugin({
uglifyOptions: {
//生产环境自动删除 console
warnings: false,
compress: {
// warnings: false, // 若打包错误,则注释这行
drop_debugger: true,
drop_console: true,
pure_funcs: ['console.log']
}
},
//日志文件
sourceMap: false,
//是否开启并行化
parallel: true,
})
)
}
}
}
三、webpack-bundle-analyzer 分析包
分析包在打包完成后会打开一个webpack页面,会显示打包后包大小占比结构,清晰明了
$ npm i webpack-bundle-analyzer -D
module.exports = {
chainWebpack: config => {
if (process.env.NODE_ENV === 'production') {
// 启动时动态创建一个 html:http://localhost:8888/report.html
// config.plugin('webpack-bundleanalyzer').use(require('webpack-bundleanalyzer').BundleAnalyzerPlugin);
// 生成一个静态 html,report.html
config.plugin('webpack-report').use(require('webpackbundle-analyzer').BundleAnalyzerPlugin, [
{
analyzerMode: 'static'
}
])
}
}
}
新的学习,新的发现,打个笔记不迷路。。。