Webpack打包优化

引言

随着项目的功能不断增加, webpack打包后文件体积变得非常大, 超过1M的文件让首次访问加载页面时比较慢, 耗时6.5s左右, 所以需要优化一下.

同时, 项目中有很多console.log, debugger, 需要在打包的时候去掉.

GZIP压缩

安装插件依赖

1
npm i --save-dev compression-webpack-plugin@1.1.12

vue.config.js中配置压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const CompressionWebpackPlugin = require('compression-webpack-plugin')
module.exports = {
transpileDependencies: ['element-ui'],
chainWebpack(config) {
config
.when(process.env.NODE_ENV !== 'development',
// 对超过10kb的文件gzip压缩
config => config.plugin('compressionPlugin').use(
new CompressionWebpackPlugin({
test: /\.(js|css|html|png|svg|woff2|eot|woff|ttf)$/, // 匹配文件名
threshold: 10240
})
)
)
}
}

压缩效果

js效果图
js效果图

css效果图
css效果图

Nginx中配置gzip

Nginxhttp配置中加入gzip_static on;

1
2
3
4
5
6
7
8
9
10
11
12
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip_static on;
server {

}
}

去console和debugger

vue-cli工具中已经引入了terser-webpack-plugin, 因此在项目中可以直接引入terser-webpack-plugin, 无需安装.

vue.config.js中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
configureWebpack: {
performance: {
hints: false
},
optimization: {
minimize: process.env.NODE_ENV === 'production',
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true, // 移除所有console相关代码;
drop_debugger: true, // 移除自动断点功能;
pure_funcs: ['console.log', 'console.error']// 配置移除指定的指令,如console.log,alert等
},
format: {
comments: false
}
},
extractComments: false
})
]
}
}
}