Understanding Tapable: Hooks and Flow Control in Webpack
Tapable is a flow‑control library used by webpack that implements synchronous and asynchronous hook mechanisms, enabling plugins to subscribe and publish events through a standardized interface, as demonstrated by source code analysis and generated function examples.
Tapable is a flow‑control library used by webpack that provides synchronous and asynchronous hook mechanisms for plugin communication.
The library centers on the Hook class, which manages a list of tapped functions (taps) and provides methods such as tap, tapAsync, tapPromise for subscription and call, callAsync, promise for publishing.
When creating a hook, an args array defines the number of parameters passed to tapped functions; the SyncHook example shows instantiation, registration with tap, and invocation via call.
const syncHook = new SyncHook(["name", "age"]);
syncHook.tap("1", (name, age, sex) => { console.log("1", name, age, sex); return 1; });
syncHook.tap("2", (name, age) => { console.log("2", name, age); return 2; });
syncHook.call("zs", 18, "男");The source code analysis breaks down the internal implementation: the _tap method normalizes options, validates name, stores type and fn, runs interceptors, and inserts the options into the taps array.
_tap(type, options, fn) {
if (typeof options === "string") { options = { name: options.trim() }; }
else if (typeof options !== "object" || options === null) { throw new Error("Invalid tap options"); }
// … validation and insertion …
}Event publishing uses _createCall, which calls the compile method; each hook type (SyncHook, AsyncParallelHook, etc.) implements a factory that generates a Function via new Function(args, body).
The article then shows the generated function code for various hooks: SyncHook, AsyncParallelHook, AsyncSeriesHook, SyncBailHook, AsyncParallelBailHook, AsyncSeriesBailHook, SyncWaterfallHook, AsyncSeriesWaterfallHook, SyncLoopHook, and AsyncSeriesLoopHook, illustrating how results propagate, bail behavior, waterfall chaining, and looping.
// SyncHook generated function
(function anonymous(name, age) {
"use strict";
var _x = this._x;
var _fn0 = _x[0]; _fn0(name, age);
var _fn1 = _x[1]; _fn1(name, age);
})();Finally, tapable employs lazy delegation: the first call to call reassigns this.call to the compiled function, avoiding repeated compilation.
const CALL_DELEGATE = function(...args) {
this.call = this._createCall("sync");
return this.call(...args);
};Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.