当我们项目打包上线时,发现build后的包体积很大,最终导首屏加载速度慢。Gzip就是能非常明显有效的解决这个问题,它的原理是把原js、css文件进行压缩,从而减小文件体积,加快首屏访问速度
以下是Gzip的相关配置
1.在vue项目中找到vue.conf.js文件(老版本在config/index.js&build/webpack.prod.conf.js 中配置)
2.在文件头部引入compression-webpack-plugin & 定义压缩文件类型 配置如下
3.在下方增加plugins关键配置即可
vue.conf.js完整代码
// 导入compression-webpack-plugin
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 定义压缩文件类型
const productionGzipExtensions = ['js', 'css']
module.exports = {
pages: {
index: {
entry: "src/main.js",
// template: "public/index.html",
// filename: "index.html",
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: "商户后台管理"
}
},
// 修复HMR
chainWebpack: config => {
config.resolve.symlinks(true);
},
// 端口配置
devServer: {
// host: "192.168.1.200",
port: 8080, // 端口号
hotOnly: false,
https: false, // https:{type:Boolean}
open: true, //配置自动启动浏览器
proxy: null // 配置跨域处理,只有一个代理
},
css: {
sourceMap: false,
loaderOptions: {
// 引入sass公共变量文件
sass: {
prependData: `@import "@/assets/element-variables.scss";`
}
}
},
configureWebpack: {
plugins: [
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8
})
]
},
// 是否启用eslint
lintOnSave: false,
// 打包时不生成.map文件
productionSourceMap: false,
};
4.我们在终端运行 npm run build,会发现有.gz文件,证明成功了!如果dist文件夹提交变大了是正常现象,因为我们没有删除源文件
5.最后一步就是在nginx.conf配置Gzip
user root;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
#gzip_http_version 1.0;
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;
gzip_vary off;
gzip_disable "MSIE [1-6].";
proxy_buffering off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
client_max_body_size 10M;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name xxx;
}
}
6.重启nginx 并用站长Gzip检测工具检测一下 ,大功告成!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。