全棧03 開啟Gzip壓縮
阿新 • • 發佈:2018-11-10
開啟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 }) ) }