Webpack本質基於事件流,流程就是將各個插件串聯執行,實現此功能的核心就是tapable,webpack中負責編譯的Compiler是基於tapable實現。webpack
SyncHook,
SyncBailHook,
SyncWaterfallHook,
SyncLoopHook,
AsyncParallelHook,
AsyncParallelBailHook,
AsyncSeriesHook,
AsyncSeriesBailHook,
AsyncSeriesWaterfallHook
複製代碼
SyncHook 基本使用web
let { SyncHook } = require('tapable');
//觸發此事件需傳入name參數,而後監聽函數能夠獲取name參數
let hooks = new SyncHook(["name", "age"]);
//註冊監聽
hooks.tap("a", function (name, age) {
console.log(name, age,'a');
});
hooks.tap("b", function (name, age) {
console.log(name, age,'b');
// 返回值無效
return 'error'
});
hooks.tap("c", function (name, age) {
console.log(name, age,'c');
});
// 觸發事件
hooks.call("測試");
複製代碼
打印結果:api
測試 100 a
測試 100 b
測試 100 c
複製代碼
SyncHook 實現原理 既然能夠new,說明就是一個類,實現比較簡單,代碼定義以下:bash
class SyncHook {
constructor() {
this.hooks = [];
}
tap(name, fn) {
this.hooks.push(fn);
}
call() {
this.hooks.forEach((hook) => hook(...arguments));
}
}
複製代碼