From ec2b316cbcbde631c0cbefc2da33477491033353 Mon Sep 17 00:00:00 2001 From: harpsealjs Date: Wed, 3 Jul 2024 16:55:19 +0800 Subject: [PATCH] docs: update compilation hooks (#7018) * docs: compilation hooks * docs: compilation hooks * Update website/docs/zh/api/plugin-api/compilation-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/compilation-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/compilation-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/stats-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/stats-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/stats-hooks.mdx Co-authored-by: neverland * Update website/docs/zh/api/plugin-api/stats-hooks.mdx Co-authored-by: neverland --------- Co-authored-by: neverland --- website/docs/en/api/plugin-api/_meta.json | 3 +- .../en/api/plugin-api/compilation-hooks.mdx | 362 ++++++++++++++++- .../docs/en/api/plugin-api/stats-hooks.mdx | 94 +++++ website/docs/zh/api/plugin-api/_meta.json | 3 +- .../zh/api/plugin-api/compilation-hooks.mdx | 366 +++++++++++++++++- .../docs/zh/api/plugin-api/stats-hooks.mdx | 92 +++++ 6 files changed, 882 insertions(+), 38 deletions(-) create mode 100644 website/docs/en/api/plugin-api/stats-hooks.mdx create mode 100644 website/docs/zh/api/plugin-api/stats-hooks.mdx diff --git a/website/docs/en/api/plugin-api/_meta.json b/website/docs/en/api/plugin-api/_meta.json index 06f246999bd..9715c9b0344 100644 --- a/website/docs/en/api/plugin-api/_meta.json +++ b/website/docs/en/api/plugin-api/_meta.json @@ -4,5 +4,6 @@ "compilation-hooks", "normal-module-factory-hooks", "context-module-factory-hooks", - "javascript-modules-plugin-hooks" + "javascript-modules-plugin-hooks", + "stats-hooks" ] diff --git a/website/docs/en/api/plugin-api/compilation-hooks.mdx b/website/docs/en/api/plugin-api/compilation-hooks.mdx index 23bdf27f6a8..9e119adad8c 100644 --- a/website/docs/en/api/plugin-api/compilation-hooks.mdx +++ b/website/docs/en/api/plugin-api/compilation-hooks.mdx @@ -1,49 +1,377 @@ +import { Badge } from '@theme'; + # Compilation Hooks -## `buildModule` +:::info +The main compilation logic of Rspack runs on the Rust side. For factors such as stability, performance, and architecture, after the Rust side compilation objects are transferred to the JavaScript side when using hooks, the modifications on these objects will not be synchronized to the Rust side. Therefore, most of hooks are "read-only". +::: -`SyncHook<[JsModule]>` +## `buildModule` -Triggered before a module build has started, can be used to modify the module (Rspack currently only support reading the module, modifying is not supported yet). + -## `processAssets` +Triggered before a module build has started。 -`AsyncSeriesHook<[CompilationAssets]>` +- **Type:** `SyncHook<[Module]>` +- **Arguments:** + - `Module`: module instance -Process the assets before emit. +```ts +type Module = { + context?: string; + resource?: string; + request?: string; + userRequest?: string; + rawRequest?: string; + factoryMeta?: JsFactoryMeta; + buildInfo: Record; + buildMeta: Record; + originalSource(): { + isRaw: boolean; + isBuffer: boolean; + source: Buffer; + map?: Buffer; + } | null; + identifier(): string; + nameForCondition(): string | null; +}; +``` -## `optimizeModules` +## `executeModule` -`SyncBailHook<[JsModule[]]>` + -Called at the beginning of the module optimization phase. A plugin can tap into this hook to perform optimizations on modules. +If there exists compiled-time execution modules, this hook will be called when they are executed. -## `optimizeChunkModule` +- **Type:** `SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>` +- **Arguments:** + - `ExecuteModuleArgument`: arguments of compiled-time execution module + - `ExecuteModuleContext`: context of compiled-time execution module -`AsyncSeriesBailHook<[JsModule[]]>` +```ts +type ExecuteModuleArgument = { + codeGenerationResult: { + get(sourceType: string): string; + }; + moduleObject: { + id: string; + exports: any; + loaded: boolean; + error?: Error; + }; +}; -Called after the tree optimization, at the beginning of the chunk modules optimization. A plugin can tap into this hook to perform optimizations of chunk modules. +type ExecuteModuleContext = { + __webpack_require__: (id: string) => any; +}; +``` ## `succeedModule` -`SyncHook<[JsModule]>` + Executed when a module has been built successfully. +- **Type:** `SyncHook<[Module]>` +- **Arguments:** + - `Module`: module instance + ## `finishModules` -`AsyncSeriesHook<[JsModule[]]>` + Called when all modules have been built without errors. +- **Type:** `AsyncSeriesHook<[Module[]]>` +- **Arguments:** + - `Module[]`: List of module instances + +## `optimizeModules` + + + +Called at the beginning of the module optimization phase. + +- **Type:** `SyncBailHook<[Module[]]>` +- **Arguments:** + - `Module[]`: list of module instances + +## `afterOptimizeModules` + + + +Called after modules optimization has completed. + +- **Type:** `SyncBailHook<[Module[]]>` +- **Arguments:** + - `Module[]`: list of module instances + +## `optimizeTree` + + + +Called before optimizing the dependency tree. + +- **Type:** `AsyncSeriesHook<[Chunk[], Module[]]>` +- **Arguments:** + - `Chunk[]`: list of chunk instances + - `Module[]`: list of module instances + +```ts +type Chunk = { + name?: string; + id?: string; + ids: string[]; + idNameHints: string[]; + filenameTemplate?: string; + cssFilenameTemplate?: string; + files: Set; + runtime: Set; + hash?: string; + contentHash: Record; + renderedHash?: string; + chunkReason?: string; + auxiliaryFiles: Set; + isOnlyInitial(): boolean; + canBeInitial(): boolean; + hasRuntime(): boolean; + groupsIterable: Set; + getAllAsyncChunks(): Set; + getAllInitialChunks(): Set; + getAllReferencedChunks(): Set; +}; +``` + +## `optimizeChunkModules` + + + +Called after the tree optimization, at the beginning of the chunk modules optimization. + +- **Type:** `AsyncSeriesBailHook<[Chunk[], Module[]]>` +- **Arguments:** + - `Chunk[]`: list of chunk instances + - `Module[]`: list of module instances + +## `additionalTreeRuntimeRequirements` + + + +Called after the tree runtime requirements collection. + +- **Type:** `SyncHook<[Chunk, Set]>` +- **Arguments:** + - `Chunk`: chunk instance + - `Set`: runtime requirements + +```ts +enum RuntimeGlobals {} +``` + +## `runtimeModule` + + + +Called after a runtime module is added into the compilation. + +- **Type:** `SyncHook<[RuntimeModule, Chunk]>` +- **Arguments:** + - `RuntimeModule`: runtime module instance + - `Chunk`: chunk instance + +```ts +type RuntimeModule = { + source?: { + isRaw: boolean; + isBuffer: boolean; + source: Buffer; + map?: Buffer; + }; + moduleIdentifier: string; + constructorName: string; + name: string; +}; +``` + +## `processAssets` + +Process the assets before emit. + +- **Type:** `AsyncSeriesHook` +- **Arguments:** + - `Assets`: list of asset instances + +```ts +type Assets = Record< + string, + { + source(): string | ArrayBuffer; + buffer(): Buffer; + size(): number; + map(options?: MapOptions): RawSourceMap | null; + sourceAndMap(options?: MapOptions): SourceAndMapResult; + } +>; +``` + +## `afterProcessAssets` + + + +Called after the [processAssets](#processAssets) hook had finished without error. + +- **Type:** `SyncHook` +- **Arguments:** + - `Assets`: list of asset instances + +## `afterSeal` + + + +Called after the seal phase. + +- **Type:** `AsyncSeriesHook<[]>` + ## `chunkHash` -`SyncHook<[JsChunk, Hash]>` + + +Triggered to emit the hash for each chunk. -Triggered when calculating the chunk hash for a chunk. +- **Type:** `SyncHook<[Chunk, Hash]>` +- **Arguments:** + - `Chunk`: chunk instance + - `Hash`: chunk hash instance + +```ts +type Hash = { + update(data: string | Buffer, inputEncoding?: string): Hash; + digest(encoding?: string): string | Buffer; +}; +``` ## `chunkAsset` -`SyncHook<[JsChunk[], string /** filename*/ ]>` + Triggered when an asset from a chunk was added to the compilation. + +- **Type:** `SyncHook<[Chunk, string]>` +- **Arguments:** + - `Chunk`: chunk instance + - `string`: asset filename + +## `childCompiler` + + + +Executed after setting up a child compiler. + +- **Type:** `SyncHook<[Compiler, string, number]>` +- **Arguments:** + - `Compiler`: child compiler instance + - `string`: child compiler name + - `number`: child compiler index + +## `statsPreset` + + + +This hook is like a list of actions that gets triggered when a preset is used. It takes in an options object. When a plugin manages a preset, it should change settings in this object carefully without replacing existing ones. + +- **Type:** `SyncHook<[Partial, CreateStatsOptionsContext]>` +- **Arguments:** + - `Partial`: stats options + - `CreateStatsOptionsContext`: stats context + +```ts +type StatsOptions = { + // `stats` in compiler options +}; + +type CreateStatsOptionsContext = { + forToString?: boolean; + [key: string]: any; +}; +``` + +Here's an illustrative plugin example: + +```js +compilation.hooks.statsPreset.for('my-preset').tap('MyPlugin', options => { + if (options.all === undefined) options.all = true; +}); +``` + +This plugin ensures that for the preset `"my-preset"`, if the `all` option is undefined, it defaults to `true`. + +## `statsNormalize` + + + +This hook is used to transform an options object into a consistent format that can be easily used by subsequent hooks. It also ensures that missing options are set to their default values. + +- **Type:** `SyncHook<[Partial, CreateStatsOptionsContext]>` +- **Arguments:** + - `Partial`: stats options + - `CreateStatsOptionsContext`: stats context + +Here's an illustrative plugin example: + +```js +compilation.hooks.statsNormalize.tap('MyPlugin', options => { + if (options.myOption === undefined) options.myOption = []; + + if (!Array.isArray(options.myOption)) options.myOptions = [options.myOptions]; +}); +``` + +In this plugin, if the `myOption` is missing, it sets it to `[]`. Additionally, it ensures that `myOption` is always an array even if it was originally defined as a single value. + +## `statsFactory` + + + +This hook provides access to the StatsFactory class for specific options. + +- **Type:** `SyncHook<[StatsFactory, StatsOptions]>` +- **Arguments:** + - `StatsFactory`: stats factory instance, see [Stats Factory Hooks](/api/plugin-api/stats-hooks#statsfactory) for more details + - `StatsOptions`: stats options + +```ts +type StatsFactory = { + hooks: StatsFactoryHooks; + create( + type: string, + data: any, + baseContext: Omit, + ): void; +}; +``` + +## `statsPrinter` + + + +This hook provides access to the StatsPrinter class for specific options. + +- **Type:** `SyncHook<[StatsPrinter, StatsOptions]>` +- **Arguments:** + - `StatsPrinter`: stats printer instance, see [Stats Printer Hooks](/api/plugin-api/stats-hooks#statsprinter) for more details. + - `StatsOptions`: stats options + +```ts +type StatsPrinter = { + hooks: StatsPrinterHooks; + print( + type: string, + object: { + [key: string]: any; + }, + baseContext?: { + [key: string]: any; + }, + ): string; +}; +``` diff --git a/website/docs/en/api/plugin-api/stats-hooks.mdx b/website/docs/en/api/plugin-api/stats-hooks.mdx new file mode 100644 index 00000000000..4f8cda37025 --- /dev/null +++ b/website/docs/en/api/plugin-api/stats-hooks.mdx @@ -0,0 +1,94 @@ +# Stats Hooks + +## StatsFactory + +### StatsFactory.hooks.extract + +A HookMap, called when generating the specified stats item. + +- **Type:** `HookMap>` +- **Arguments:** + - `Object`: result stats item object which properties should be added. + - `Class`: the original data of the stats item + - `StatsFactoryContext`: generating context + +```ts +type StatsFactoryContext = { + type: string; + makePathsRelative?: ((arg0: string) => string) | undefined; + compilation?: Compilation | undefined; + cachedGetErrors?: ((arg0: Compilation) => JsStatsError[]) | undefined; + cachedGetWarnings?: ((arg0: Compilation) => JsStatsWarning[]) | undefined; +}; +``` + +For the following example, the `customProperty` attribute is added in the finally generated `stats.compilation` through `MyPlugin`: + +```js +compilation.hooks.statsFactory.tap('MyPlugin', (statsFactory, options) => { + statsFactory.hooks.extract + .for('compilation') + .tap('MyPlugin', (object, compilation) => { + object.customProperty = MyPlugin.getCustomValue(compilation); + }); +}); +``` + +### StatsFactory.hooks.result + +A HookMap, called after generating the specified stats item. + +- **Type:** `HookMap>` +- **Arguments:** + - `any[]`:generated stats item result + - `StatsFactoryContext`:generating context + +## StatsPrinter + +### StatsPrinter.hooks.print + +A HookMap, called + +为一个 HookMap, called when generating the printed string of the specified stats item. + +- **Type:** `HookMap>` +- **Arguments:** + - `Object`:stats item object + - `StatsPrinterContext`:printing context + +```ts +type StatsPrinterContext = { + type?: string; + compilation?: StatsCompilation; + chunkGroup?: StatsChunkGroup; + asset?: StatsAsset; + module?: StatsModule; + chunk?: StatsChunk; + moduleReason?: StatsModuleReason; + bold?: (str: string) => string; + yellow?: (str: string) => string; + red?: (str: string) => string; + green?: (str: string) => string; + magenta?: (str: string) => string; + cyan?: (str: string) => string; + formatFilename?: (file: string, oversize?: boolean) => string; + formatModuleId?: (id: string) => string; + formatChunkId?: + | ((id: string, direction?: 'parent' | 'child' | 'sibling') => string) + | undefined; + formatSize?: (size: number) => string; + formatDateTime?: (dateTime: number) => string; + formatFlag?: (flag: string) => string; + formatTime?: (time: number, boldQuantity?: boolean) => string; + chunkGroupKind?: string; +}; +``` + +### StatsPrinter.hooks.result + +A HookMap, called after generating the printed string of the specified stats item. + +- **Type:** `HookMap>` +- **Arguments:** + - `String`: printed string of the stats item + - `StatsPrinterContext`: printing context diff --git a/website/docs/zh/api/plugin-api/_meta.json b/website/docs/zh/api/plugin-api/_meta.json index 06f246999bd..9715c9b0344 100644 --- a/website/docs/zh/api/plugin-api/_meta.json +++ b/website/docs/zh/api/plugin-api/_meta.json @@ -4,5 +4,6 @@ "compilation-hooks", "normal-module-factory-hooks", "context-module-factory-hooks", - "javascript-modules-plugin-hooks" + "javascript-modules-plugin-hooks", + "stats-hooks" ] diff --git a/website/docs/zh/api/plugin-api/compilation-hooks.mdx b/website/docs/zh/api/plugin-api/compilation-hooks.mdx index 1911b7d4069..30837a1b1a1 100644 --- a/website/docs/zh/api/plugin-api/compilation-hooks.mdx +++ b/website/docs/zh/api/plugin-api/compilation-hooks.mdx @@ -1,49 +1,377 @@ +import { Badge } from '@theme'; + # Compilation 钩子 -## `buildModule` +:::info +Rspack 主要编译逻辑运行在 Rust 侧。出于稳定性、性能、架构等因素,在使用钩子时 Rust 侧编译对象传输到 JavaScript 侧后,对 JavaScript 侧的修改不会被同步到 Rust 侧。因此绝大部分钩子为“只读”。 +::: -`SyncHook<[JsModule]>` +## `buildModule` -在模块被构建之前调用,可以用来修改模块(Rspack 目前仅支持读) + -## `processAssets` +在模块被构建之前调用。 -`AsyncSeriesHook<[CompilationAssets]>` +- **类型:** `SyncHook<[Module]>` +- **参数:** + - `Module`:模块实例 -在产物输出之前进行修改产物。 +```ts +type Module = { + context?: string; + resource?: string; + request?: string; + userRequest?: string; + rawRequest?: string; + factoryMeta?: JsFactoryMeta; + buildInfo: Record; + buildMeta: Record; + originalSource(): { + isRaw: boolean; + isBuffer: boolean; + source: Buffer; + map?: Buffer; + } | null; + identifier(): string; + nameForCondition(): string | null; +}; +``` -## `optimizeModules` +## `executeModule` -`SyncBailHook<[JsModule[]]>` + -在模块优化阶段开始时调用。插件可以使用此钩子来对模块执行优化。 +若存在编译期执行模块,将在模块被执行时调用。 -## `optimizeChunkModule` +- **类型:** `SyncHook<[ExecuteModuleArgument, ExecuteModuleContext]>` +- **参数:** + - `ExecuteModuleArgument`:模块运行参数 + - `ExecuteModuleContext`:模块运行上下文 -`AsyncSeriesBailHook<[JsModule[]]>` +```ts +type ExecuteModuleArgument = { + codeGenerationResult: { + get(sourceType: string): string; + }; + moduleObject: { + id: string; + exports: any; + loaded: boolean; + error?: Error; + }; +}; -在 `afterOptimizeTree` 之后,在块模块优化的开始时调用。插件可以使用此钩子来对块模块执行优化。 +type ExecuteModuleContext = { + __webpack_require__: (id: string) => any; +}; +``` ## `succeedModule` -`SyncHook<[JsModule]>` + -在模块成功构建后调用 +在模块成功构建后调用。 + +- **类型:** `SyncHook<[Module]>` +- **参数:** + - `Module`:模块实例 ## `finishModules` -`AsyncSeriesHook<[JsModule[]]>` + 当所有模块都没有错误地构建完成时调用。 +- **类型:** `AsyncSeriesHook<[Module[]]>` +- **参数:** + - `Module[]`:所有模块列表 + +## `optimizeModules` + + + +在模块优化阶段开始时调用。 + +- **类型:** `SyncBailHook<[Module[]]>` +- **参数:** + - `Module[]`:所有模块列表 + +## `afterOptimizeModules` + + + +在模块优化完成之后调用。 + +- **类型:** `SyncBailHook<[Module[]]>` +- **参数:** + - `Module[]`:所有模块列表 + +## `optimizeTree` + + + +在优化依赖树之前调用。 + +- **类型:** `AsyncSeriesHook<[Chunk[], Module[]]>` +- **参数:** + - `Chunk[]`:Chunk 列表: + - `Module[]`:模块列表 + +```ts +type Chunk = { + name?: string; + id?: string; + ids: string[]; + idNameHints: string[]; + filenameTemplate?: string; + cssFilenameTemplate?: string; + files: Set; + runtime: Set; + hash?: string; + contentHash: Record; + renderedHash?: string; + chunkReason?: string; + auxiliaryFiles: Set; + isOnlyInitial(): boolean; + canBeInitial(): boolean; + hasRuntime(): boolean; + groupsIterable: Set; + getAllAsyncChunks(): Set; + getAllInitialChunks(): Set; + getAllReferencedChunks(): Set; +}; +``` + +## `optimizeChunkModules` + + + +在树优化之后,chunk 模块优化开始时调用。 + +- **类型:** `AsyncSeriesBailHook<[Chunk[], Module[]]>` +- **参数:** + - `Chunk[]`:Chunk 列表: + - `Module[]`:模块列表 + +## `additionalTreeRuntimeRequirements` + + + +在树运行时依赖计算完成后调用。 + +- **类型:** `SyncHook<[Chunk, Set]>` +- **参数:** + - `Chunk`:Chunk 实例 + - `Set`:运行时依赖 + +```ts +enum RuntimeGlobals {} +``` + +## `runtimeModule` + + + +在运行时模块被添加后调用。 + +- **类型:** `SyncHook<[RuntimeModule, Chunk]>` +- **参数:** + - `RuntimeModule`:运行时模块 + - `Chunk`:Chunk 实例 + +```ts +type RuntimeModule = { + source?: { + isRaw: boolean; + isBuffer: boolean; + source: Buffer; + map?: Buffer; + }; + moduleIdentifier: string; + constructorName: string; + name: string; +}; +``` + +## `processAssets` + +在产物输出之前进行修改产物。 + +- **类型:** `AsyncSeriesHook` +- **参数:** + - `Assets`:产物资源映射表 + +```ts +type Assets = Record< + string, + { + source(): string | ArrayBuffer; + buffer(): Buffer; + size(): number; + map(options?: MapOptions): RawSourceMap | null; + sourceAndMap(options?: MapOptions): SourceAndMapResult; + } +>; +``` + +## `afterProcessAssets` + + + +在 [processAssets](#processAssets) hook 无错误执行后调用。 + +- **类型:** `SyncHook` +- **参数:** + - `Assets`:产物资源映射表 + +## `afterSeal` + + + +在 seal 阶段结束后调用。 + +- **类型:** `AsyncSeriesHook<[]>` + ## `chunkHash` -`SyncHook<[JsChunk, Hash]>` + + +触发来为每个 chunk 生成 hash。 -当计算 Chunk 的 chunk hash 时触发。 +- **类型:** `SyncHook<[Chunk, Hash]>` +- **参数:** + - `Chunk`:Chunk 实例 + - `Hash`:Chunk 哈希实例 + +```ts +type Hash = { + update(data: string | Buffer, inputEncoding?: string): Hash; + digest(encoding?: string): string | Buffer; +}; +``` ## `chunkAsset` -`SyncHook<[JsChunk[], string /** filename*/ ]>` + + +一个 chunk 中的一个 asset 被添加到 compilation 时调用。 + +- **类型:** `SyncHook<[Chunk, string]>` +- **参数:** + - `Chunk`:Chunk 实例 + - `string`:产物文件名 + +## `childCompiler` + + + +创建子 compiler 之后调用。 + +- **类型:** `SyncHook<[Compiler, string, number]>` +- **参数:** + - `Compiler`:子编译实例: + - `string`:子编译名称 + - `number`:子编译索引 + +## `statsPreset` + + + +当使用预设 stats 配置时触发。接收一个 stats 配置对象,当插件管理 stats 预设配置时,它应当在配置对象上仔细地修改,而非直接替换整个配置对象。 + +- **类型:** `SyncHook<[Partial, CreateStatsOptionsContext]>` +- **参数:** + - `Partial`:Stats 配置 + - `CreateStatsOptionsContext`:Stats 上下文 + +```ts +type StatsOptions = { + // 见构建配置中的 stats +}; + +type CreateStatsOptionsContext = { + forToString?: boolean; + [key: string]: any; +}; +``` + +以如下插件为例: + +```js +compilation.hooks.statsPreset.for('my-preset').tap('MyPlugin', options => { + if (options.all === undefined) options.all = true; +}); +``` + +该插件确保对于预设 `"my-preset"`,如果 `all` 选项未定义,则默认为 `true`。 + +## `statsNormalize` + + + +此钩子用于将选项对象转换为便于后续钩子使用的格式。它还确保缺失的选项被设置为默认值。 + +- **类型:** `SyncHook<[Partial, CreateStatsOptionsContext]>` +- **参数:** + - `Partial`:Stats 配置 + - `CreateStatsOptionsContext`:Stats 上下文 + +以如下插件为例: + +```js +compilation.hooks.statsNormalize.tap('MyPlugin', options => { + if (options.myOption === undefined) options.myOption = []; + + if (!Array.isArray(options.myOption)) options.myOptions = [options.myOptions]; +}); +``` + +在这个插件中,如果 `myOption` 缺失,会将其设置为 `[]`。此外,它确保 `myOption` 始终是一个数组,即使它最初被定义为单个值。 + +## `statsFactory` + + + +此钩子提供了对 `StatsFactory` 的访问,以调用其钩子。该类用于构造 Stats 对象。 + +- **类型:** `SyncHook<[StatsFactory, StatsOptions]>` +- **参数:** + - `StatsFactory`:Stats 工厂实例,详见 [Stats Factory 钩子](/api/plugin-api/stats-hooks#statsfactory) + - `StatsOptions`:Stats 配置 + +```ts +type StatsFactory = { + hooks: StatsFactoryHooks; + create( + type: string, + data: any, + baseContext: Omit, + ): void; +}; +``` + +## `statsPrinter` + + + +此钩子提供了对 `StatsPrinter` 的访问,以调用其钩子。该类用于打印 Stats 信息。 + +- **类型:** `SyncHook<[StatsPrinter, StatsOptions]>` +- **参数:** + - `StatsPrinter`:Stats 打印实例,详见 [Stats Printer 钩子](/api/plugin-api/stats-hooks#statsprinter) + - `StatsOptions`:Stats 配置 -当 Chunk 的产物被添加到编译时触发。 +```ts +type StatsPrinter = { + hooks: StatsPrinterHooks; + print( + type: string, + object: { + [key: string]: any; + }, + baseContext?: { + [key: string]: any; + }, + ): string; +}; +``` diff --git a/website/docs/zh/api/plugin-api/stats-hooks.mdx b/website/docs/zh/api/plugin-api/stats-hooks.mdx new file mode 100644 index 00000000000..658f24b57d1 --- /dev/null +++ b/website/docs/zh/api/plugin-api/stats-hooks.mdx @@ -0,0 +1,92 @@ +# Stats 钩子 + +## StatsFactory + +### StatsFactory.hooks.extract + +`StatsFactory.hooks.extract` 是一个 HookMap,在生成指定的 stats 项目时触发。 + +- **类型:** `HookMap>` +- **参数:** + - `Object`:该 stats 项目的结果对象,将属性添加于此对象 + - `Class`:该 stats 项目对应的原始数据 + - `StatsFactoryContext`:生成上下文 + +```ts +type StatsFactoryContext = { + type: string; + makePathsRelative?: ((arg0: string) => string) | undefined; + compilation?: Compilation | undefined; + cachedGetErrors?: ((arg0: Compilation) => JsStatsError[]) | undefined; + cachedGetWarnings?: ((arg0: Compilation) => JsStatsWarning[]) | undefined; +}; +``` + +如以下例子,通过 `MyPlugin` 在最终生成的 `stats.compilation` 中添加 `customProperty` 属性: + +```js +compilation.hooks.statsFactory.tap('MyPlugin', (statsFactory, options) => { + statsFactory.hooks.extract + .for('compilation') + .tap('MyPlugin', (object, compilation) => { + object.customProperty = MyPlugin.getCustomValue(compilation); + }); +}); +``` + +### StatsFactory.hooks.result + +`StatsFactory.hooks.result` 是一个 HookMap,在生成指定 stats 项目后触发。 + +- **类型:** `HookMap>` +- **参数:** + - `any[]`:该 stats 项目的生成结果 + - `StatsFactoryContext`:生成上下文 + +## StatsPrinter + +### StatsPrinter.hooks.print + +`StatsPrinter.hooks.print` 是一个 HookMap,在生成指定的 stats 项目的打印字符串时触发。 + +- **类型:** `HookMap>` +- **参数:** + - `Object`:该 stats 项目 + - `StatsPrinterContext`:打印上下文 + +```ts +type StatsPrinterContext = { + type?: string; + compilation?: StatsCompilation; + chunkGroup?: StatsChunkGroup; + asset?: StatsAsset; + module?: StatsModule; + chunk?: StatsChunk; + moduleReason?: StatsModuleReason; + bold?: (str: string) => string; + yellow?: (str: string) => string; + red?: (str: string) => string; + green?: (str: string) => string; + magenta?: (str: string) => string; + cyan?: (str: string) => string; + formatFilename?: (file: string, oversize?: boolean) => string; + formatModuleId?: (id: string) => string; + formatChunkId?: + | ((id: string, direction?: 'parent' | 'child' | 'sibling') => string) + | undefined; + formatSize?: (size: number) => string; + formatDateTime?: (dateTime: number) => string; + formatFlag?: (flag: string) => string; + formatTime?: (time: number, boldQuantity?: boolean) => string; + chunkGroupKind?: string; +}; +``` + +### StatsPrinter.hooks.result + +`StatsPrinter.hooks.result` 是一个 HookMap,在生成指定的 stats 项目的打印字符串后触发。 + +- **类型:** `HookMap>` +- **参数:** + - `String`:该 stats 项目打印字符串 + - `StatsPrinterContext`:打印上下文