Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork109
Prepare compressed versions of assets to serve them with Content-Encoding
License
webpack/compression-webpack-plugin
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Prepare compressed versions of assets to serve them with Content-Encoding.
To begin, you'll need to installcompression-webpack-plugin:
npm install compression-webpack-plugin --save-devor
yarn add -D compression-webpack-pluginor
pnpm add -D compression-webpack-pluginThen add the plugin to yourwebpack config. For example:
webpack.config.js
constCompressionPlugin=require("compression-webpack-plugin");module.exports={plugins:[newCompressionPlugin()],};
Finally, runwebpack using the method you normally use (e.g., via CLI or an npm script).
Type:
typetest=string|RegExp|(string|RegExp)[];
Default:undefined
Include all assets that pass test assertion.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({test:/\.js(\?.*)?$/i,}),],};
Type:
typeinclude=string|RegExp|(string|RegExp)[];
Default:undefined
Include all assets matching any of these conditions.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({include:/\/includes/,}),],};
Type:
typeexclude=string|RegExp|(string|RegExp)[];
Default:undefined
Exclude all assets matching any of these conditions.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({exclude:/\/excludes/,}),],};
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,)=>void);
Defines the compression algorithm or function to use. Defaults togzip.
Note
If you use a custom function for thealgorithm option, the default value ofcompressionOptions will be an empty object{}.
The algorithm is based on the Node.jszlib module.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({algorithm:"gzip",}),],};
Allow you to specify a custom compression function.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({algorithm(input,compressionOptions,callback){returncompressionFunction(input,compressionOptions,callback);},}),],};
Type:
interfacecompressionOptions{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 available options in thezlib documentation.
Note
If you use a custom function for thealgorithm option, the default value ofcompressionOptions will be an empty object{}.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({compressionOptions:{level:1},}),],};
Type:
typethreshold=number;
Default:0
Only assets larger than this size (in bytes) are processed.
webpack.config.js
module.exports={plugins:[newCompressionPlugin({threshold:8192,}),],};
Type:
typeminRatio=number;
Default:0.8
Only assets that compress better than this ratio are processed (minRatio = Compressed Size / Original Size).For example, if you have aimage.png file with a size of 1024 bytes, and its compressed version is of 768 bytes, theminRatio is0.75.In other words, assets will be processed only when the ratio ofCompressed Size / Original Size is less than the specifiedminRatio.
You can use a value of1 to process assets that are smaller than or equal to the original size.
Use a value ofInfinity to process all assets, even if they are larger than the original size or their original size is0 bytes (useful when you are pre-zipping all assets for AWS).
Use a value ofNumber.MAX_SAFE_INTEGER to process all assets even if they are larger than the original size, excluding assets with their original size is0 bytes.
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_INTEGERminRatio:0.8,}),],};
Type:
typefilename=string|((pathdata:PathData)=>string);
Default:"[path][base].gz"
The target asset filename.
For example, given an asset path:assets/images/image.png?foo=bar#hash:
[path] is replaced with the directories of the original asset, including the trailing/ (assets/images/).
[file] is replaced with the path of the original asset (assets/images/image.png).
[base] is replaced with the base name ([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, including the. (.png).
[query] is replaced with the query of the original asset, including the? (?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",}),],};
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` notationif(/\.svg$/.test(pathData.filename)){return"assets/svg/[path][base].gz";}return"assets/js/[path][base].gz";},}),],};
Type:
typedeleteOriginalAssets=|boolean|"keep-source-map"|((name:string)=>boolean);
Default:false
Determines whether the original (uncompressed) assets should be deleted after compression.
If set to
true, all original assets will be deleted.If set to
"keep-source-map", all original assets except source maps (.mapfiles) will be deleted.If a function is provided, it will be called with each asset’s name and should return
trueto delete the asset orfalseto keep it.
Example:
module.exports={plugins:[newCompressionPlugin({deleteOriginalAssets:(assetName)=>// Delete all assets except images!assetName.endsWith(".png")&&!assetName.endsWith(".jpg"),}),],};
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;},}),],};
Prepare compressed versions of assets using thezopfli library.
Note
@gfx/zopfli requires at leastNode.js version8.
To begin, you'll need to install@gfx/zopfli:
$npm install @gfx/zopfli --save-devwebpack.config.js
constzopfli=require("@gfx/zopfli");module.exports={plugins:[newCompressionPlugin({compressionOptions:{numiterations:15,},algorithm(input,compressionOptions,callback){returnzopfli.gzip(input,compressionOptions,callback);},}),],};
Brotli is a compression algorithm originally developed by Google, and offers compression superior to gzip.
Node.js v10.16.0 and later includesnative support for Brotli compression in itszlib module.
You can take advantage of this built-in support for Brotli in Node 10.16.0 and later by just passing in the appropriatealgorithm to the CompressionPlugin:
webpack.config.js
constzlib=require("node: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_QUALITY option is functionally equivalent to zlib’slevel option.You can find all Brotli’s options inthe relevant part of the zlib module documentation.
Zstandard (zstd) is a fast lossless compression algorithm, targeting real-time compression scenarios at zlib-level and better compression ratios.
Node.js 22.15.0 and later includesnative support for Zstandard compression in itszlib module.
You can take advantage of this built-in support for zstd in Node 22.15.0 and later by just passing in the appropriatealgorithm to the CompressionPlugin:
webpack.config.js
constzlib=require("node:zlib");module.exports={plugins:[newCompressionPlugin({filename:"[path][base].zst",algorithm:"zstdCompress",test:/\.(js|css|html|svg)$/,compressionOptions:{params:{[zlib.constants.ZSTD_c_compressionLevel]:10,},},threshold:10240,minRatio:0.8,deleteOriginalAssets:false,}),],};
You can find all Zstandard's options inthe relevant part of the zlib module documentation.
webpack.config.js
constzlib=require("node: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,}),],};
We welcome contributions!
Please take a moment to read our contributing guidelines if you haven't yet done so.
About
Prepare compressed versions of assets to serve them with Content-Encoding
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.