當我們項目打包上線時,發現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.2
})
]
},
// 是否啓用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檢測工具檢測一下 ,大功告成!