Skip to content

webpack 打包时生成 html、css、js 的 .gz 文件

js
module.exports = {
  chainWebpack (config) {
    config
      .plugin('CompressionPlugin')
      .use('compression-webpack-plugin', [
        {
          filename: '[path][base].gz', // 文件名
          test: /\.(js|css|html)$/, // gzip 压缩的文件
          threshold: 10240, // 大于 10KiB 的文件才会被压缩
          algorithm: 'gzip', // 压缩方式
          minRatio: 0.8 // 压缩比小于这个值才压缩
        }
      ])
      .end()
  }
}

请求

Accept-Encoding: gzip

响应

js
// 获取浏览器支持的压缩方式
req.headers['accept-encoding'] // output: 'gzip, deflate, br'

// 如果存在对应的 .gz 文件,就将响应头中的 Content-Encoding 字段设置为 gzip。
res.setHeader('Content-Encoding', 'gzip')
// 然后读取对应的 .gz 文件并返回,浏览器会自动进行解压缩。
createReadStream(`${ reqFilePath }.gz`).pipe(res)