1. 程式人生 > >全棧03 開啟Gzip壓縮

全棧03 開啟Gzip壓縮

開啟Gzip可以壓縮靜態檔案的下載體積

Express

Express 4.0 以下版本:

var express = require('express');
var app = express();
app.use(express.compress());

Express 4.0 以上版本:

var compression = require('compression');
var express = require('express');
var app = express();
app.use(compression());

Koa

const koa = require('koa');
const compress = require('koa-compress');

const app = koa();

const options = { threshold: 2048 };
app.use(compress(options));

webpack

webpack.prod.conf.js中,引入了compression-webpack-plugin,用來生成一個被gzip壓縮過的JS檔案

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

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

參考