Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

compression-webpack-plugin

webpack-contrib3.6mMIT11.1.0TypeScript support: included

Prepare compressed versions of assets to serve them with Content-Encoding

webpack

readme

npm node tests cover discussion size

compression-webpack-plugin

Prepare compressed versions of assets to serve them with Content-Encoding.

Getting Started

To begin, you'll need to install compression-webpack-plugin:

npm install compression-webpack-plugin --save-dev

or

yarn add -D compression-webpack-plugin

or

pnpm add -D compression-webpack-plugin

Then add the plugin to your webpack config. For example:

webpack.config.js

const CompressionPlugin = require("compression-webpack-plugin");

module.exports = {
  plugins: [new CompressionPlugin()],
};

And run webpack via your preferred method.

Options

test

Type:

type test = string | RegExp | Array<string | RegExp>;

Default: undefined

Include all assets that pass test assertion.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      test: /\.js(\?.*)?$/i,
    }),
  ],
};

include

Type:

type include = string | RegExp | Array<string | RegExp>;

Default: undefined

Include all assets matching any of these conditions.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      include: /\/includes/,
    }),
  ],
};

exclude

Type:

type exclude = string | RegExp | Array<string | RegExp>;

Default: undefined

Exclude all assets matching any of these conditions.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      exclude: /\/excludes/,
    }),
  ],
};

algorithm

Type:

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: "string"): string;
            },
      ) => void,
    ) => any);

Default: gzip

The compression algorithm/function.

Note

If you use custom function for the algorithm option, the default value of the compressionOptions option is {}.

string

The algorithm is taken from zlib.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      algorithm: "gzip",
    }),
  ],
};

function

Allow to specify a custom compression function.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      algorithm(input, compressionOptions, callback) {
        return compressionFunction(input, compressionOptions, callback);
      },
    }),
  ],
};

compressionOptions

Type:

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;
};

Default: { level: 9 }

Compression options for algorithm.

You can find all options here zlib.

Note

If you use custom function for the algorithm option, the default value is {}.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      compressionOptions: { level: 1 },
    }),
  ],
};

threshold

Type:

type threshold = number;

Default: 0

Only assets bigger than this size are processed. In bytes.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      threshold: 8192,
    }),
  ],
};

minRatio

Type:

type minRatio = number;

Default: 0.8

Only assets that compress better than this ratio are processed (minRatio = Compressed Size / Original Size). Example: you have image.png file with 1024b size, compressed version of file has 768b size, so minRatio equal 0.75. In other words assets will be processed when the Compressed Size / Original Size value less minRatio value.

You can use 1 value to process assets that are smaller than the original.

Use a value of Infinity to process all assets even if they are larger than the original size or their original size is 0 bytes (useful when you are pre-zipping all assets for AWS).

Use a value of Number.MAX_SAFE_INTEGER to process all assets even if they are larger than the original size, excluding assets with their original size is 0 bytes.

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:

type filename = string | ((pathdata: PathData) => string);

Default: "[path][base].gz"

The target asset filename.

string

For example we have assets/images/image.png?foo=bar#hash:

[path] is replaced with the directories to the original asset, included trailing / (assets/images/).

[file] is replaced with the path of original asset (assets/images/image.png).

[base] is replaced with the base ([name] + [ext]) of the original asset (image.png).

[name] is replaced with the name of the original asset (image).

[ext] is replaced with the extension of the original asset, included . (.png).

[query] is replaced with the query of the original asset, included ? (?foo=bar).

[fragment] is replaced with the fragment (in the concept of URL it is called hash) of the original asset (#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:

type deleteOriginalAssets =
  | boolean
  | "keep-source-map"
  | ((name: string) => boolean);

Default: false

Whether to delete the original assets or not.

webpack.config.js

module.exports = {
  plugins: [
    new CompressionPlugin({
      deleteOriginalAssets: true,
    }),
  ],
};

To exclude sourcemaps from compression:

module.exports = {
  plugins: [
    new CompressionPlugin({
      exclude: /.map$/,
      deleteOriginalAssets: "keep-source-map",
    }),
  ],
};

Using a custom function:

module.exports = {
  plugins: [
    new CompressionPlugin({
      exclude: /.map$/,
      deleteOriginalAssets: (name) => {
        if (/\.js$/.test(name)) {
          return false;
        }

        return true;
      },
    }),
  ],
};

Examples

Using Zopfli

Prepare compressed versions of assets using zopfli library.

Note

@gfx/zopfli require minimum 8 version of node.

To begin, you'll need to install @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);
      },
    }),
  ],
};

Using Brotli

Brotli is a compression algorithm originally developed by Google, and offers compression superior to gzip.

Node 10.16.0 and later has native support for Brotli compression in its zlib module.

We can take advantage of this built-in support for Brotli in Node 10.16.0 and later by just passing in the appropriate algorithm to the 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,
    }),
  ],
};

Note Brotli’s BROTLI_PARAM_QUALITY option is functionally equivalent to zlib’s level option. You can find all Brotli’s options in the relevant part of the zlib module documentation.

Multiple compressed versions of assets for different algorithm

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

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

11.1.0 (2024-02-27)

Features

  • support the deleteOriginalAssets option as a function (#380) (1be8955)

Bug Fixes

11.0.0 (2024-01-15)

⚠ BREAKING CHANGES

  • minimum supported Node.js version is 18.12.0 (2ef7b37)

10.0.0 (2022-05-17)

⚠ BREAKING CHANGES

  • default filename is [path][base].br for brotli (#286)
  • minimum supported Node.js version is 14.15.0 (#301)

Bug Fixes

  • default filename is [path][base].br for brotli (#286) (db04e14)
  • minimum supported Node.js version is 14.15.0 (#301) (5db3255)

9.2.0 (2021-12-16)

Features

  • removed cjs wrapper and generated types in commonjs format (export = and namespaces used in types), now you can directly use exported types (#277) (8664d36)

9.1.2 (2021-12-13)

Bug Fixes

9.1.1 (2021-12-09)

Bug Fixes

  • added types to package.json (0acff90)

9.1.0 (2021-12-09)

Features

9.0.1 (2021-11-17)

Chore

  • update schema-utils package to 4.0.0 version

9.0.0 (2021-09-11)

⚠ BREAKING CHANGES

  • pathData as first argument of a custom function for the filename option was changed, now we pass only pathData.filename, see example

Features

  • migrate on webpack API for getting filename (59fe68c)
  • output documentation links on errors (#255) (8624e44)

8.0.1 (2021-06-25)

Chore

  • update serialize-javascript

8.0.0 (2021-05-21)

⚠ BREAKING CHANGES

  • minimum supported Node.js version is 12.13.0

7.1.2 (2021-01-11)

Bug Fixes

  • crash when filename and algorithm options are functions (#241) (f33424a)

7.1.1 (2020-12-25)

Bug Fixes

7.1.0 (2020-12-18)

Features

  • compress assets added later by plugins (5b8b356)

Bug Fixes

  • compatibility with workbox-webpack-plugin (#234) (5d54128)
  • perf

7.0.0 (2020-12-02)

⚠ BREAKING CHANGES

  • minimum supported webpack version is ^5.1.0
  • the cache option was removed, the plugin respects caching from configurations, please read

6.1.1 (2020-11-12)

Bug Fixes

  • compatibility with child compilations (5e3bb95)

6.1.0 (2020-11-09)

Features

  • added the keep-source-maps value to the deleteOriginalAssets option (#216) (bd60650)

6.0.5 (2020-11-02)

Bug Fixes

  • allowed compressed assets to overwrite original assets using the deleteOriginalAssets option (62d3d0a)

6.0.4 (2020-10-26)

Bug Fixes

  • always set compression level to maximum for the custom algorithm (483f328)

6.0.3 (2020-10-09)

Chore

  • update schema-utils

6.0.2 (2020-09-19)

Bug Fixes

6.0.1 (2020-09-16)

Bug Fixes

6.0.0 (2020-09-14)

⚠ BREAKING CHANGES

  • default value of the filename option was changed to "[path][base].gz"
  • removed the [dir] placeholder, please use the [path] placeholder
  • the Function type of the filename option should return value with placeholders, please see an example

Features

  • added [fragment], [base] and [path] placeholders for the filename option

Bug Fixes

  • caching (#194) (9de2a88)
  • respect immutable flag for assets

5.0.2 (2020-09-02)

Bug Fixes

  • do not crash when the algorithm option return non Buffer (#190) (81bf601)

5.0.1 (2020-08-22)

Bug Fixes

  • compatibility with webpack@5 (84e367b)

5.0.0 (2020-08-17)

⚠ BREAKING CHANGES

  • default value of the filename option is '[path].gz'
  • use processAssets hook for webpack@5 compatibility, it can create incompatibility with plugins that do not support webpack@5, please open an issue in their repositories

Features

  • improve compatibility with webpack@5 (1f9674e)
  • improve stats output for webpack@5

Bug Fixes

  • fix persistent cache between builds

4.0.1 (2020-08-12)

Bug Fixes

4.0.0 (2020-05-12)

⚠ BREAKING CHANGES

Features

  • enable cache by default for webpack@4 (#164) (ea33463)

Bug Fixes

  • behaviour in watch mode (e222c4e)

3.1.0 (2020-01-09)

Features

  • add dir, name and ext placeholders in filename option (#144) (bf22024)

Bug Fixes

3.0.0 (2019-06-05)

chore

Tests

BREAKING CHANGES

  • deps: minimum required nodejs version is 8.9.0

2.0.0 (2018-09-04)

Features

  • filename option now accept {String} value
  • validation schema for plugin options

BREAKING CHANGES

  • enforces peerDependencies of "webpack": "^4.3.0"
  • enforces engines of "node": ">= 6.9.0 <7.0.0 || >= 8.9.0
  • compressed options (options.level, options.flush, options.dictionary and etc) grouped into compressionOptions option
  • asset option was removed (use filename option instead)
  • default value of filename option is now [path].gz[query]

1.1.12 (2018-08-29)

Bug Fixes

  • correct handling filename with query (#105) (c8d7757)

1.1.11 (2018-03-09)

Performance Improvements

  • index: switch to md4 for content hashing (#103) (0eebc46)

1.1.10 (2018-02-27)

Performance Improvements

1.1.9 (2018-02-26)

Bug Fixes

  • package: add webpack >= 4 (peerDependencies) (#101) (d3c29e7)

1.1.8 (2018-02-23)

Bug Fixes

  • index: tapable deprecation warnings (webpack >= v4.0.0) (#100) (d6ccdc4)

1.1.7 (2018-02-16)

Bug Fixes

  • index: reduce memory usage (cacheKey.hash) (#97) (3c77d43)

1.1.6 (2018-01-29)

1.1.5 (2018-01-29)

Bug Fixes

  • package: use prepare instead of prepublish for release (0b90a71)

1.1.4 (2018-01-29)

Bug Fixes

  • missing options include and exclude (#95) (cc44bcb)

1.1.3 (2017-12-22)

Bug Fixes

1.1.2 (2017-12-14)

Bug Fixes

  • text/include/exclude option behaviour (#88) (1d0a840)

1.1.1 (2017-12-14)

Bug Fixes

  • index: don't use JSON.stringify() to serialize the cache data (options.cache) (#87) (0d22741)

1.1.0 (2017-12-14)

Features

  • add cache option (options.cache) (#86) (49a8a77)
  • add include and exclude options (options.include|options.exclude) (#82) (1ce3024)

1.0.1 (2017-09-29)

Code Refactoring

  • Use emit event instead of this-compilation (#71) (9ebc852)

1.0.0 (2017-07-15)

Code Refactoring

BREAKING CHANGES

Migration:

  • npm i -D zopfli-webpack-plugin
  • The Zopfli API has remained the same, those who were using the Zopfli option in this plugin should just need to switch plugins.

1.0.0-beta.1 (2017-07-03)

Code Refactoring

  • Drops optional Zopfli dependency (#65) (328048a)

BREAKING CHANGES

  • The optional dependency for Zopfli was causing issues in consumers CI / CD chains, this option has now been removed.

MIGRATION: Zopfli is now in it's own plugin the options have remained the same. For those using the Zopfli option in compression-webpack-plugin swap it out for https://github.com/webpack-contrib/zopfli-webpack-plugin

1.0.0-beta.0 (2017-06-24)

Code Refactoring

BREAKING CHANGES

Migration:

  • npm i -D zopfli-webpack-plugin
  • The Zopfli API has remained the same, those who were using the Zopfli option in this plugin should just need to switch plugins.

0.4.0 (2017-04-08)

Features

  • add option to change the filename (#51) (fb7bd81)
  • add option to delete original assets (#44) (24f15f2)

0.3.2 (2016-09-13)

Chores

  • Update node-zopfli version (2d3dd44)

0.3.1 (2016-03-26)

Bug Fixes

  • TypeError Invalid non-strig/buffer chunk (53ec8a9)

0.3.0 (2016-01-23)

Bug Fixes

Features

  • Add compression level option (9d05172)
  • Add node-zopfli option (2c22b1c)
  • Permit {path} and {query} in asset name (12d167c)

0.2.0 (2015-04-08)

Features

0.1.2 (2015-04-08)

Bug Fixes

  • Double compression on worker-loader bundles (7ce2b32)
  • Remove unneeded module.exports (6f4e60d)