vue.config.js配置文件
'use strict'
const path = require('path')
const CompressionPlugin = require('compression-webpack-plugin')
module.exports = {
// ...其他配置
configureWebpack: {
// ...其他webpack配置
plugins: [
// Gzip压缩配置
new CompressionPlugin({
test: /\.(js|css|html)?$/i, // 需要压缩的文件类型
filename: '[path][base].gz', // 压缩后的文件命名
algorithm: 'gzip', // 压缩算法
minRatio: 0.8, // 压缩率阈值
deleteOriginalAssets: false // 是否删除原文件
}),
// Brotli压缩配置
new CompressionPlugin({
test: /\.(js|css|html)?$/i, // 需要压缩的文件类型
filename: '[path][base].br', // 压缩后的文件命名
algorithm: 'brotliCompress', // Brotli压缩算法
minRatio: 0.8, // 压缩率阈值
deleteOriginalAssets: false // 是否删除原文件
// 移除compressionOptions配置,使用默认值以避免兼容性问题
})
],
},
// ...其他配置
}
构建成功后,可以在dist目录下看到同时生成了原文件、.gz和.br三种文件格式。
Nginx服务器配置
为了让浏览器能够正确请求并接收压缩文件,我们还需要在Nginx服务器上进行相应配置。以下是完整的Nginx Brotli配置示例:
# nginx.conf
# 加载Brotli模块(放在http块之外)
load_module modules/ngx_http_brotli_filter_module.so;
load_module modules/ngx_http_brotli_static_module.so;
http {
server {
listen 8999;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location ^~/xxx/files/ {
alias /home/xxx/files/;
}
location ^~/xxx/ {
proxy_pass http://127.0.0.1:8899/xxx/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
root /home/dist;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
gzip on;
gzip_min_length 1024;
gzip_types application/json text/plain application/javascript application/x-javascript text/javascript text/xml text/css font/ttf font/x-woff;
gzip_vary on;
gzip_comp_level 4;
gzip_buffers 16 8k;
gzip_http_version 1.1;
brotli on; # 开启Brotli压缩
brotli_static on; # 启用静态文件压缩
brotli_types text/plain text/css application/javascript application/json application/xml image/svg+xml application/x-font-ttf; # 支持的文件类型
brotli_comp_level 6; # 压缩级别(1-11)
brotli_buffers 16 8k; # 压缩缓冲区
brotli_min_length 20; # 最小压缩文件大小
}
# ...其他服务器配置
}
最佳实践建议
- 同时配置Gzip和Brotli:Brotli作为主要压缩方式,Gzip作为降级方案,确保所有浏览器都能获得压缩体验
- 预压缩静态资源:在构建阶段生成压缩文件,而不是在服务器运行时动态压缩,减少服务器负载
- 合理设置压缩阈值:只压缩较大的文件(通常设置为1KB以上),避免对小文件进行压缩反而增加大小
- 定期更新浏览器兼容性列表:根据目标用户群体的浏览器分布,调整支持的压缩算法