Skip to content

webpack-contrib/compression-webpack-plugin

Repository files navigation

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 installcompression-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 yourwebpackconfig. For example:

webpack.config.js

constCompressionPlugin=require("compression-webpack-plugin");

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

And runwebpackvia your preferred method.

Options

test

Type:

typetest=string|RegExp|Array<string|RegExp>;

Default:undefined

Include all assets that pass test assertion.

webpack.config.js

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

include

Type:

typeinclude=string|RegExp|Array<string|RegExp>;

Default:undefined

Include all assets matching any of these conditions.

webpack.config.js

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

exclude

Type:

typeexclude=string|RegExp|Array<string|RegExp>;

Default:undefined

Exclude all assets matching any of these conditions.

webpack.config.js

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

algorithm

Type:

typealgorithm=
|string
|((
input:Buffer,
options:CompressionOptions,
callback:(
error:Error|null|undefined,
result:
|string
|ArrayBuffer
|SharedArrayBuffer
|Uint8Array
|readonlynumber[]
|{
valueOf():ArrayBuffer|SharedArrayBuffer;
}
|{
valueOf():string|Uint8Array|readonlynumber[];
}
|{
valueOf():string;
}
|{
[Symbol.toPrimitive](hint:"string"):string;
},
)=>void,
)=>any);

Default:gzip

The compression algorithm/function.

Note

If you use custom function for thealgorithmoption, the default value of thecompressionOptionsoption is{}.

string

The algorithm is taken fromzlib.

webpack.config.js

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

function

Allow to specify a custom compression function.

webpack.config.js

module.exports={
plugins:[
newCompressionPlugin({
algorithm(input,compressionOptions,callback){
returncompressionFunction(input,compressionOptions,callback);
},
}),
],
};

compressionOptions

Type:

typecompressionOptions={
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 foralgorithm.

You can find all options herezlib.

Note

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

webpack.config.js

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

threshold

Type:

typethreshold=number;

Default:0

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

webpack.config.js

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

minRatio

Type:

typeminRatio=number;

Default:0.8

Only assets that compress better than this ratio are processed (minRatio = Compressed Size / Original Size). Example: you haveimage.pngfile with 1024b size, compressed version of file has 768b size, sominRatioequal0.75. In other words assets will be processed when theCompressed Size / Original Sizevalue lessminRatiovalue.

You can use1value to process assets that are smaller than the original.

Use a value ofInfinityto process all assets even if they are larger than the original size or their original size is0bytes (useful when you are pre-zipping all assets for AWS).

Use a value ofNumber.MAX_SAFE_INTEGERto process all assets even if they are larger than the original size, excluding assets with their original size is0bytes.

webpack.config.js

module.exports={
plugins:[
newCompressionPlugin({
// 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:

typefilename=string|((pathdata:PathData)=>string);

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

The target asset filename.

string

For example we haveassets/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 calledhash) of the original asset (#hash).

webpack.config.js

module.exports={
plugins:[
newCompressionPlugin({
filename:"[path][base].gz",
}),
],
};

function

webpack.config.js

module.exports={
plugins:[
newCompressionPlugin({
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:

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

Default:false

Whether to delete the original assets or not.

webpack.config.js

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

To exclude sourcemaps from compression:

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

Using a custom function:

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

returntrue;
},
}),
],
};

Examples

Using Zopfli

Prepare compressed versions of assets usingzopflilibrary.

Note

@gfx/zopflirequire minimum8version ofnode.

To begin, you'll need to install@gfx/zopfli:

$npm install @gfx/zopfli --save-dev

webpack.config.js

constzopfli=require("@gfx/zopfli");

module.exports={
plugins:[
newCompressionPlugin({
compressionOptions:{
numiterations:15,
},
algorithm(input,compressionOptions,callback){
returnzopfli.gzip(input,compressionOptions,callback);
},
}),
],
};

Using Brotli

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

Node 10.16.0 and later hasnative supportfor 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 appropriatealgorithmto the CompressionPlugin:

webpack.config.js

constzlib=require("zlib");

module.exports={
plugins:[
newCompressionPlugin({
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’sBROTLI_PARAM_QUALITYoption is functionally equivalent to zlib’sleveloption. You can find all Brotli’s options inthe relevant part of the zlib module documentation.

Multiple compressed versions of assets for different algorithm

webpack.config.js

constzlib=require("zlib");

module.exports={
plugins:[
newCompressionPlugin({
filename:"[path][base].gz",
algorithm:"gzip",
test:/\.js$|\.css$|\.html$/,
threshold:10240,
minRatio:0.8,
}),
newCompressionPlugin({
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