准备资产的压缩版本,以便通过 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
(例如,通过 CLI 或 npm 脚本)。
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
该算法基于 Node.js 的 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` 选项使用自定义函数,则 `compressionOptions` 的默认值将为空对象
{}
。
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 = 压缩大小 / 原始大小
)。例如,如果你有一个大小为 1024 字节的 image.png
文件,其压缩版本为 768 字节,则 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
确定原始(未压缩)资产是否应在压缩后删除。
如果设置为 true
,所有原始资产都将被删除。
如果设置为 "keep-source-map"
,除源映射(.map
文件)外的所有原始资产都将被删除。
如果提供一个函数,它将与每个资产的名称一起调用,并应返回 true
删除资产或 false
保留资产。
示例
module.exports = {
plugins: [
new CompressionPlugin({
deleteOriginalAssets: (assetName) => {
// Delete all assets except images
return !assetName.endsWith(".png") && !assetName.endsWith(".jpg");
},
}),
],
};
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
要求Node.js
版本至少为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 是 Google 最初开发的一种压缩算法,提供优于 gzip 的压缩效果。
Node.js v10.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,
}),
],
};
[!NOTE] Brotli 的 BROTLI_PARAM_QUALITY
选项在功能上等同于 zlib 的 level
选项。你可以在 zlib 模块文档的相关部分中找到所有 Brotli 的选项。
Zstandard (zstd) 是一种快速无损压缩算法,旨在实现 zlib 级别及更高压缩比的实时压缩场景。
Node.js 22.15.0 及更高版本在其 zlib
模块中包含了对 Zstandard 压缩的原生支持。
你可以在 Node 22.15.0 及更高版本中利用对 zstd 的这种内置支持,只需将适当的 algorithm
传递给 CompressionPlugin 即可。
webpack.config.js
const zlib = require("zlib");
module.exports = {
plugins: [
new CompressionPlugin({
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,
}),
],
};
你可以在 zlib 模块文档的相关部分中找到所有 Zstandard 的选项。
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,
}),
],
};
我们欢迎贡献!
如果你尚未阅读,请花一点时间阅读我们的贡献指南。