CompressionWebpackPlugin

免責聲明: CompressionWebpackPlugin 是由社群成員維護的第三方套件,它可能不具備與 webpack 相同的支援、安全政策或授權,且並非由 webpack 維護。

npm node tests cover discussion size

準備壓縮版本的資產,以 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 值來處理小於原始大小的資產。

使用 Infinity 值來處理所有資產,即使它們大於原始大小或其原始大小為 0 位元組(在您為 AWS 預先壓縮所有資產時很有用)。

使用 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",
    }),
  ],
};

function

webpack.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

使用 zopfli 函式庫準備壓縮版本的資產。

注意

@gfx/zopfli 需要 node 的最低版本為 8

首先,您需要安裝 @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

Brotli 是一種壓縮演算法,最初由 Google 開發,其壓縮效果優於 gzip。

Node 10.16.0 及更新版本在其 zlib 模組中具有 原生支援 Brotli 壓縮。

我們可以利用 Node 10.16.0 及更新版本中對 Brotli 的內建支援,只要將適當的 algorithm 傳遞給 CompressionPlugin 即可

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 選項。您可以在 zlib 模組文件中的相關部分 找到 Brotli 的所有選項。

針對不同演算法產生多個壓縮版本的資產

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,
    }),
  ],
};

貢獻

如果您尚未閱讀我們的貢獻指南,請花點時間閱讀。

貢獻

授權

MIT