配置完以下相关内容后响应头会多出Content-Encoding: gzip,即成功配置
安装插件
npm i compression-webpack-plugin@6.1.1
vue.config.js配置
const compressionPlugin = require('compression-webpack-plugin');//引入gzip压缩插件
// 暴露配置项,会合并到webpack里
module.exports = {
chainWebpack(config) {
// ......
},
configureWebpack: config => {
// 开发环境不配置
if (process.env.NODE_ENV !== 'production') return
// 生产环境才去配置
return {
plugins: [
new compressionPlugin({ //此插件不能使用太高的版本,否则报错:TypeError: Cannot read property 'tapPromise' of undefined
// filename: "[path][base].gz", // 这种方式是默认的,多个文件压缩就有多个.gz文件,建议使用下方的写法
filename: '[path].gz[query]', // 使得多个.gz文件合并成一个文件,这种方式压缩后的文件少,建议使用
algorithm: 'gzip',//开启压缩方式
test: /\.js$|\.css$|\.html$|\.ttf$|\.eot$|\.woff$/, // 使用正则给匹配到的文件做压缩,这里是给html、css、js以及字体(.ttf和.woff和.eot)做压缩
threshold: 10240, //以字节为单位压缩超过这个的文件,使用默认值10240
minRatio: 0.8, // 最小压缩比率,官方默认0.8
deleteOriginalAssets: false
//是否删除原有静态资源文件,即只保留压缩后的.gz文件,建议这个置为false,还保留源文件。原因: // 如果出现访问.gz文件访问不到的时候,还可以访问源文件。
})
]
}
},
};
后端Nginx相关配置
server {
listen 80;
server_name localhost;
location / {
try_files $uri $uri/ /index.html;
root C:/nginx-1.18.0/html/gzip/dist;
index index.html index.htm;
}
location /api/ {
proxy_pass http://localhost:8090/;
}
gzip on;
gzip_static on; //当存在.gzip格式的js文件时,优先使用静态文件
gzip_min_length 10k; //开启gzip压缩的最小大小
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2; #级别,1-9,理论上数字越大压缩的越好,也越占用CPU时间,但是cpu确是有点浪费。因为2就够用了
gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml; ```
# 压缩的文件类型 MIME类型
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
}