Content-Encodingで提供するために、アセットの圧縮バージョンを準備します。
まず、compression-webpack-pluginをインストールする必要があります。
npm install compression-webpack-plugin --save-dev
または
yarn add -D compression-webpack-plugin
または
pnpm add -D compression-webpack-plugin
次に、プラグインをwebpackの設定に追加します。例:
webpack.config.js
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
plugins: [new CompressionPlugin()],
};そして、お好みの方法でwebpackを実行します。
testタイプ
type test = string | RegExp | Array<string | RegExp>;デフォルト: undefined
テストアサーションをパスしたすべてのアセットを含めます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
test: /\.js(\?.*)?$/i,
}),
],
};includeタイプ
type include = string | RegExp | Array<string | RegExp>;デフォルト: undefined
これらのいずれかの条件に一致するすべてのアセットを含めます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
include: /\/includes/,
}),
],
};excludeタイプ
type exclude = string | RegExp | Array<string | RegExp>;デフォルト: undefined
これらのいずれかの条件に一致するすべてのアセットを除外します。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
exclude: /\/excludes/,
}),
],
};algorithmタイプ
type algorithm =
| string
| ((
input: Buffer,
options: CompressionOptions,
callback: (
error: Error | null | undefined,
result:
| string
| ArrayBuffer
| SharedArrayBuffer
| Uint8Array
| readonly number[]
| {
valueOf(): ArrayBuffer | SharedArrayBuffer;
}
| {
valueOf(): string | Uint8Array | readonly number[];
}
| {
valueOf(): string;
}
| {
[Symbol.toPrimitive](hint:%20%22string%22): string;
},
) => void,
) => any);デフォルト: gzip
圧縮アルゴリズム/関数。
注
algorithmオプションにカスタム関数を使用する場合、compressionOptionsオプションのデフォルト値は{}です。
stringアルゴリズムはzlibから取得されます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
algorithm: "gzip",
}),
],
};functionカスタム圧縮関数を指定できます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
algorithm(input, compressionOptions, callback) {
return compressionFunction(input, compressionOptions, callback);
},
}),
],
};compressionOptionsタイプ
type compressionOptions = {
flush?: number;
finishFlush?: number;
chunkSize?: number;
windowBits?: number;
level?: number;
memLevel?: number;
strategy?: number;
dictionary?: Buffer | TypedArray | DataView | ArrayBuffer;
info?: boolean;
maxOutputLength?: number;
};デフォルト: { level: 9 }
algorithmの圧縮オプション。
すべてのオプションはzlibで確認できます。
注
algorithmオプションにカスタム関数を使用する場合、デフォルト値は{}です。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
compressionOptions: { level: 1 },
}),
],
};thresholdタイプ
type threshold = number;デフォルト: 0
このサイズより大きいアセットのみが処理されます。単位はバイトです。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
threshold: 8192,
}),
],
};minRatioタイプ
type minRatio = number;デフォルト: 0.8
この比率よりも圧縮率が高いアセットのみが処理されます(minRatio = 圧縮後のサイズ / 元のサイズ)。例:1024bサイズのimage.pngファイルがあり、ファイルの圧縮バージョンが768bサイズの場合、minRatioは0.75になります。言い換えると、圧縮後のサイズ / 元のサイズの値がminRatioの値より小さい場合にアセットが処理されます。
元のサイズよりも小さいアセットを処理するには、1の値を使用できます。
元のサイズよりも大きい場合や、元のサイズが0バイトの場合でもすべてのアセットを処理するには、Infinityの値を使用してください(AWSですべてのアセットを事前にzip圧縮する場合に役立ちます)。
元のサイズよりも大きい場合でもすべてのアセットを処理するには、Number.MAX_SAFE_INTEGERの値を使用してください。ただし、元のサイズが0バイトのアセットは除外されます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
// Compress all assets, including files with `0` bytes size
// minRatio: Infinity
// Compress all assets, excluding files with `0` bytes size
// minRatio: Number.MAX_SAFE_INTEGER
minRatio: 0.8,
}),
],
};filenameタイプ
type filename = string | ((pathdata: PathData) => string);デフォルト: "[path][base].gz"
ターゲットアセットのファイル名。
stringたとえば、assets/images/image.png?foo=bar#hashがあるとします。
[path]は、末尾の/を含む、元のアセットへのディレクトリに置き換えられます(assets/images/)。
[file]は、元のアセットのパスに置き換えられます(assets/images/image.png)。
[base]は、元のアセットのベース([name] + [ext])(image.png)に置き換えられます。
[name]は、元のアセットの名前(image)に置き換えられます。
[ext]は、.を含む、元のアセットの拡張子(.png)に置き換えられます。
[query]は、?を含む、元のアセットのクエリ(?foo=bar)に置き換えられます。
[fragment]は、元のアセットのフラグメント(URLの概念ではhashと呼ばれる)(#hash)に置き換えられます。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
filename: "[path][base].gz",
}),
],
};functionwebpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
filename(pathData) {
// The `pathData` argument contains all placeholders - `path`/`name`/`ext`/etc
// Available properties described above, for the `String` notation
if (/\.svg$/.test(pathData.filename)) {
return "assets/svg/[path][base].gz";
}
return "assets/js/[path][base].gz";
},
}),
],
};deleteOriginalAssetsタイプ
type deleteOriginalAssets =
| boolean
| "keep-source-map"
| ((name: string) => boolean);デフォルト: false
元のアセットを削除するかどうか。
webpack.config.js
module.exports = {
plugins: [
new CompressionPlugin({
deleteOriginalAssets: true,
}),
],
};ソースマップを圧縮から除外するには
module.exports = {
plugins: [
new CompressionPlugin({
exclude: /.map$/,
deleteOriginalAssets: "keep-source-map",
}),
],
};カスタム関数を使用する
module.exports = {
plugins: [
new CompressionPlugin({
exclude: /.map$/,
deleteOriginalAssets: (name) => {
if (/\.js$/.test(name)) {
return false;
}
return true;
},
}),
],
};zopfliライブラリを使用して、アセットの圧縮バージョンを準備します。
注
@gfx/zopfliには、最低でも8バージョンのnodeが必要です。
開始するには、@gfx/zopfliをインストールする必要があります。
$ npm install @gfx/zopfli --save-dev
webpack.config.js
const zopfli = require("@gfx/zopfli");
module.exports = {
plugins: [
new CompressionPlugin({
compressionOptions: {
numiterations: 15,
},
algorithm(input, compressionOptions, callback) {
return zopfli.gzip(input, compressionOptions, callback);
},
}),
],
};Brotliは、Googleによって最初に開発された圧縮アルゴリズムであり、gzipよりも優れた圧縮を提供します。
Node 10.16.0以降では、zlibモジュールでBrotli圧縮のネイティブサポートが提供されています。
CompressionPluginに適切なalgorithmを渡すだけで、Node 10.16.0以降でBrotliのこの組み込みサポートを利用できます。
webpack.config.js
const zlib = require("zlib");
module.exports = {
plugins: [
new CompressionPlugin({
filename: "[path][base].br",
algorithm: "brotliCompress",
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
},
},
threshold: 10240,
minRatio: 0.8,
deleteOriginalAssets: false,
}),
],
};注 BrotliのBROTLI_PARAM_QUALITYオプションは、機能的にはzlibのlevelオプションと同等です。Brotliのすべてのオプションは、zlibモジュールの関連部分のドキュメントで確認できます。
webpack.config.js
const zlib = require("zlib");
module.exports = {
plugins: [
new CompressionPlugin({
filename: "[path][base].gz",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8,
}),
new CompressionPlugin({
filename: "[path][base].br",
algorithm: "brotliCompress",
test: /\.(js|css|html|svg)$/,
compressionOptions: {
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 11,
},
},
threshold: 10240,
minRatio: 0.8,
}),
],
};まだ読んでいない場合は、コントリビューションガイドラインを読む時間を作ってください。