Plugin API
我们首先回顾 tapable
工具,它提供了 webpack 插件接口的支柱。
tapable 这个小型 library 是 webpack 的一个核心工具,但也可用于其他地方,以提供类似的插件接口。webpack 中许多对象扩展自 Tapable
类。这个类暴露 tap
, tapAsync
和 tapPromise
方法,可以使用这些方法,注入自定义的构建步骤,这些步骤将在整个编译过程中不同时机触发。
请查看 文档 了解更多信息。理解三种 tap
方法以及提供这些方法的钩子至关重要。要注意到,扩展自 Tapable
的对象(例如 compiler 对象)、它们提供的钩子和每个钩子的类型(例如 SyncHook
)。
根据所使用的 钩子(hook) 和 tap
方法,插件可以以多种不同的方式运行。这个工作方式与 Tapable
提供的 密切相关。compiler hooks 分别记录了 Tapable
内在的钩子,指出哪些 tap
方法可用。
然而,对于能够使用了 AsyncHook(异步钩子)
的 run
,我们可以使用 tapAsync
或 tapPromise
(以及 tap
):
这些需求(story)的含义在于,可以有多种方式将 hook
钩入到 compiler
中,可以让各种插件都以合适的方式去运行。
为了给其他插件的编译添加一个新的钩子,来 tap(触及)
到这些插件的内部,直接从 tapable
中 require
所需的钩子类(hook class),然后创建:
再次声明,查看 tapable
来,了解更多不同的钩子类(hook class),以及它们是如何工作的。
Plugins can report progress via , which prints progress messages to stderr by default. In order to enable progress reporting, pass a --progress
argument when running the .
To report progress, a plugin must tap
into a hook using the context: true
option:
The reportProgress
function may be called with these arguments:
percentage
: This argument is unused; instead,ProgressPlugin
will calculate a percentage based on the current hook....args
: Any number of strings, which will be passed to theProgressPlugin
handler to be reported to the user.
Note that only a subset of compiler and compilation hooks support the reportProgress
function. See for a full list.
查看 compiler hooks 部分,了解所有可用的 compiler
钩子和其所需的参数的详细列表。