前端性能优化之Gzip打包
前端性能优化之Gzip打包
一、静态:webpack使用gzip打包,nginx配置gzip_static打开
1、webpack使用gzip
1)npm安装 compression-webpack-plugin 模块
2)vue.config.js中配置
const CompressionPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
// 打包压缩,更多参数参考 https://www.webpackjs.com/plugins/compression-webpack-plugin/
config.plugin('compressionPlugin')
.use(new CompressionPlugin({
filename: '[path].gz[query]', // 压缩后的文件名(保持原文件名,后缀加.gz)
algorithm: 'gzip', // 使用gzip压缩
test: productionGzipExtensions, // 匹配文件名
threshold: 10240, // 对超过10k的数据压缩
minRatio: 0.8, // 压缩率小于0.8才会压缩
deleteOriginalAssets: true // 删除原资源
}))
2)nginx配置gzip_static
在nginx.conf中http模块添加
gzip_static on;
gzip_proxied expired no-cache no-store private auth;
二、动态:nginx配置gzip打开
在nginx.conf中http模块添加
# 开启和关闭gzip模式
gzip on;
# gizp压缩起点,文件大于1k才进行压缩
gzip_min_length 1k;
# 设置压缩所需要的缓冲区大小,以4k为单位,如果文件为7k则申请2*4k的缓冲区
gzip_buffers 4 16k;
# 设置gzip压缩针对的HTTP协议版本
gzip_http_version 1.0;
# gzip 压缩级别,1-9,数字越大压缩的越好,也越占用CPU时间
gzip_comp_level 2;
# 进行压缩的文件类型
gzip_types text/plain application/javascript text/css application/xml;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
三、nginx踩坑、避坑
1)注意:nginx安装默认不带gzip_static模块
需要在编译安装时使用命令
./configure --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35 --with-http_gzip_static_module
具体安装nginx步骤,可参考菜鸟教程Nginx 安装配置