gzip简介

HTTP协议上的gzip编码是一种用来改进web应用程序性能的技术,web服务器和客户端(浏览器)必须共同支持gzip。目前主流的浏览器,Chrome,firefox,IE等都支持该协议。

简单来说,gzip是一种压缩技术。经过gzip压缩后页面大小可以变为原来的30%甚至更小,这样,用户浏览页面的时候速度会快得多。

那么客户端和服务器之间是如何通信来支持gzip的呢?通过下图我们可以很清晰的了解。
gzip编解码

nginx启用gzip

gzip on; # 开启Gzip
gzip_static on; # 开启静态文件压缩
gzip_min_length  1k; # 不压缩临界值,大于1K的才压缩
gzip_buffers     4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss; # 进行压缩的文件类型
gzip_vary on;
gzip_proxied   expired no-cache no-store private auth;
gzip_disable   "MSIE [1-6]\.";

webpack构建gz文件

前提:项目基于"webpack": “^3.6.0”

config/index.js下有如下语句:

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: true,
    productionGzipExtensions: ['js', 'css'],

1、productionGzip默认为false,将它设置为true

2、注意到上方有注释,需要先安装compression-webpack-plugin插件

3、npm install --save-dev compression-webpack-plugin安装成功后,执行npm run build却出现报错

node build/build.js
D:\Demo\node_modules\compression-webpack-plugin\node_modules\schema-> utils\dist\validate.js:104
throw new _ValidationError.default(errors, schema, configuration);
^

ValidationError: Invalid options object. Compression Plugin has been initialized using an options object that does not match the API schema.
- options has an unknown property 'asset'. These properties are valid:
object { test?, include?, exclude?, algorithm?, compressionOptions?, threshold?, minRatio?, deleteOriginalAssets?, filename? }
at validate (D:\Demo\node_modules\compression-webpack-plugin\node_modules\schema-utils\dist\validate.js:104:11)
at new CompressionPlugin (D:\Demo\node_modules\compression-webpack-plugin\dist\index.js:26:31)
at Object. (D:\Demo\build\webpack.prod.conf.js:128:5)
at Module._compile (internal/modules/cjs/loader.js:778:30)

4、根据提示,修改webpack.prod.conf.js中的配置(asset 改为 filename)

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      filename: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

5、再次执行npm run build,仍然有出现报错

node build/build.js

| building for production…D:\Demo\node_modules\compression-webpack-plugin\dist\index.js:282
compiler.hooks.thisCompilation.tap(pluginName, compilation => {
^

TypeError:Cannot read property 'thisCompilation' of undefined
at CompressionPlugin.apply (D:\Demo\node_modules\compression-webpack-plugin\dist\index.js:282:20)
at Compiler.apply (D:\Demo\node_modules\tapable\lib\Tapable.js:375:16)
at webpack (D:\Demo\node_modules\webpack\lib\webpack.js:33:19)
at err (D:\Demo\build\build.js:19:3)
at next (D:\Demo\node_modules\rimraf\rimraf.js:83:7)
at CB (D:\1Demo\node_modules\rimraf\rimraf.js:119:9)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)

查资料看,可能和插件的版本有关;
直接npm install后的版本:compression-webpack-plugin": “^7.1.2”
安装时,控制台有警告提示:compression-webpack-plugin 和 webpack 的版本不匹配

PS D:\Demo> npm install --save-dev compression-webpack-plugin
npm WARN ajv-keywords@3.5.2 requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself.
npm WARN `compression-webpack-plugin@7.1.2 requires a peer of webpack@^5.1.0 but none is installed`. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
...

6、试着 降低compression-webpack-plugin版本到1.1.12,打包成功

先卸载高版本,再安装指定版本

npm uninstall --save-dev compression-webpack-plugin
npm install --save-dev compression-webpack-plugin@1.1.12

可以看到:打包出的资源文件,压缩比还是不错滴,完美~
gzip打包文件

资源发布到服务器

访问时,通过抓包可看到 请求 和 回复 里都带有gzip标记
gzip压缩http请求

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐