应压缩基于文本的资源以最小化网络总字节数
Accept-Encoding: gzip, compress, br
兼容性:
Brotli (br):与 Internet Explorer、Safari 桌面版和 iOS 上的 Safari 不兼容
GZIP:所有主流浏览器都支持GZIP,但效率不如Brotli
前端使用compression-webpack-plugin启用Gzip压缩安装
npm install compression-webpack-plugin --save-dev
配置
//vue.config.js
const { defineConfig } = require('@vue/cli-service')
// 导入compression-webpack-plugin:压缩资源,生成.gz文件
const CompressionWebpackPlugin = require('compression-webpack-plugin')
// 定义压缩文件类型
const productionGzipExtensions = ['js', 'css']
//...其他配置
module.exports = defineConfig({
//.....其他配置
configureWebpack:{
//...其他配置
//找到plugin,添加插件
plugins: [
new CompressionWebpackPlugin({
filename: '[path][base].gz',//[file] 会被替换成原始资源。[path] 会被替换成原始资源的路径, [query] 会被替换成查询字符串
algorithm: 'gzip',//压缩成gzip
//所有匹配该正则的资源都会被处理。默认值是全部资源。
test: new RegExp('\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,//只有大小大于该值的资源会被处理。单位是 bytes。默认值是 0。
minRatio: 0.8//只有压缩率小于这个值的资源才会被处理。默认值是 0.8。
})
]
}
})
盒
可以发现生成了很多“.gz”格式的文件,并且这些文件是经过压缩的
服务器配置
生成的压缩文件不能直接使用,需要在服务器端进行配置webpack资源压缩,发现打包生成的“dist/index.html”主页并没有直接引用那些“.gz”格式的文件。
实现的关键其实就是让服务器向浏览器发送响应头“Content-Encoding=gzip”,并发送对应的“.parse资源”。
nginx 实现(nginx.conf)