什么是Gzip
前端优化:开启Gzip压缩_前端开启gzip压缩-CSDN博客
Gzip
是一种文件压缩算法,减少文件大小,节省带宽从而提减少网络传输时间,网站会更快地加载。
如何判断是否开启:
请求头:服务端会通过客户端发送的请求头中的 Accept-Encoding 字段来确定是否支持
安装compression-webpack-plugin
npm install compression-webpack-plugin --save-dev
如果打包时候出现Cannot read property 'tapPromise' of undefined 这个报错,是compression-webpack-plugin版本问题,通过降低版本就可以解
在vue.config.js中配置,引入插件
const CompressionPlugin = require('compression-webpack-plugin')
使用插件,在vue.config.js文件中configureWebpack的plugins中添加配置new CompressionPlugin(…)或如下在最后加入
module.exports = {configureWebpack: {plugins: [// gzipnew CompressionWebpackPlugin({cache: false, // 不启用文件缓存filename: '[path].gz[query]',// 压缩后的文件名algorithm: 'gzip', // 使用gzip压缩test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'), // 压缩文件格式threshold: 10240,minRatio: 0.8, // 压缩率小于1才会压缩deleteOriginalAssets: false})],resolve: {alias: {'@': resolve('src')}}},}
注意事项
-
不要删除原始文件:
deleteOriginalAssets
不建议设置为true
,因为某些浏览器可能不支持 Gzip 压缩。 -
文件大小限制:通过
threshold
设置文件大小阈值,避免对小文件进行压缩(压缩小文件可能得不偿失)。 -
兼容性:确保服务器和客户端都支持 Gzip 压缩。