之前做的Vue2项目,上线后,第一次加载时,发现特别慢,打开控制台后,发现是一个名字叫chunk-vendors.js的文件体积过大,导致首屏加载速度特别慢。这个js文件是项目中引入的第三方库打包而成的,如何解决打包后文件体积过大问题?
一、Vue2 项目打包优化
1. 使用 compression-webpack-plugin 对打包文件进行压缩
安装插件:
npm i compression-webpack-plugin@10.0.0
vue.config.js:
/ 引入
const CompressionPlugin = require('compression-webpack-plugin')
const zlib = require('zlib')
// 1. 插件配置
plugins: [
new webpack.IgnorePlugin({
resourceRegExp:/^\.\/locale$/,
contextRegExp:/moment$/}),
// compression-webpack-plugin 压缩配置
// 压缩成 .gz 文件
new CompressionPlugin({
filename: '[path][base].gz',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
// 压缩成 .br 文件,如果 zlib 报错无法解决,可以注释这段使用代码,一般本地没问题,需要注意线上服务器会可能发生找不到 zlib 的情况。
new CompressionPlugin({
filename: '[path][base].br',
algorithm: 'brotliCompress',
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11
}
},
threshold: 10240,
minRatio: 0.8
})
]
2. 使用webpack optimization 进行对大文件分包打包
vue.config.js
chainWebpack(config){
if (isProd){
config.optimization.splitChunks({
cacheGroups:{
common: {//commons 一般是是个人定义的
name: 'chunk-common', // 打包后的文件名
chunks: 'initial',
minChunks: 1,
maxInitialRequests: 5,
minSize: 0,
priority: 1,
reuseExistingChunk: true
},
vendors: {//vendor 是导入的 npm 包
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
chunks: 'initial',
maxSize: 600000,
maxInitialRequests: 20,
priority: 2,
reuseExistingChunk: true,
enforce: true
},
antDesignVue: {//把antDesignVue从chunk-vendors.js提取出来。当然我们也可以把mixins,vue.min.js等等也按照类似配置提取出来
name: 'chunk-ant-design-vue',
test: /[\\/]node_modules[\\/]ant-design-vue[\\/]/,
chunks: 'initial',
priority: 3,
maxSize: 600000,
reuseExistingChunk: true,
enforce: true
}
}
})
}
}
二、服务器配置
1. tomcat 中配置
打开 %TOMCAT_HOME%/conf/server.xml
增加以下配置(注意删除注释):
<Connector port="8085" protocol="HTTP/1.1"
connectionTimeout="20000"
compression="on" // 开启压缩 (on|off)
compressionMinSize="2048" // 启用压缩的输出内容大小,默认2KB
noCompressionUserAgents="gozilla, traviata" // 配置不开启压缩浏览器
compressableMimeType="text/html,text/xml,text/plain,text/css,application/javascript" //设置压缩文件
useSendfile="false" //useSendfile属性默认为true, 会禁用压缩, 需要设置为false
/>
2. Nginx 中配置
打开 nginx.conf
添加以下配置:
http {
# 开启gzip
gzip on;
# 启用gzip压缩的最小文件;小于设置值的文件将不会被压缩
gzip_min_length 1k;
# gzip 压缩级别 1-10
gzip_comp_level 2;
# 进行压缩的文件类型。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
}
nginx常用命令
在 nginx 安装目录中打开 cmd
启动后 访问 http://localhost:端口号 端口号在nginx.conf 查看,默认为80
1.启动
start nginx
2.停止
nginx -s stop
3.版本
nginx -v
4.热重启
nginx -s reload
5.彻底停止nginx服务
taskkill /f /t /im nginx.exe