【Webpack】1256- 硬核解析 Webpack 事件流核心!
一、Tapable 介紹
Tapable 是 Webpack 整個生命周期及其插件機制的事件流實現,它提供了多種形式的發布訂閱模式的 API,我們可以利用它來注冊自定義事件,并在不同的時機去觸發。
Tapable 對外提供了如下幾種鉤子(Hooks):
const?{SyncHook,SyncBailHook,SyncWaterfallHook,SyncLoopHook,AsyncParallelHook,AsyncParallelBailHook,AsyncSeriesHook,AsyncSeriesBailHook,AsyncSeriesWaterfallHook}?=?require("tapable");每個鉤子擁有自己專屬的事件執行機制和觸發時機,Webpack 正是利用它們,在不同的編譯階段來調用各插件回調,從而影響編譯結果。
本文來自全棧修仙源碼交流群?VaJoy 大佬,他會逐步介紹每個鉤子,并分析其源碼實現。本文內容偏硬核,建議讀者分時間耐心閱讀。
另外,本文各模塊的代碼放在 Github 上,推薦大家下載后配合本文一同食用,遇到不理解的地方可以打斷點調試,學起來會很快。
https://github.com/VaJoy/tapable-analysis
二、SyncHook 的基礎實現
2.1 介紹
SyncHook 是 Tapable 所提供的最簡單的鉤子,它是一個同步鉤子。
本小節的內容會比較長,因為會介紹到很多鉤子們共用的方法。學習完 SyncHook 鉤子的實現,再去分析其它鉤子的源碼會輕松很多。
初始化 SyncHook 后,可以通過調用實例的 tap 方法來注冊事件,調用 call 方法按注冊順序來執行回調:
//?初始化同步鉤子 const?hook?=?new?SyncHook(["contry",?"city",?"people"]);//?注冊/訂閱事件 hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap('event-2',?(contry,?city,?people)?=>?{console.log('event-2:',?contry,?city,?people) })//?執行訂閱事件回調 //?鉤子上目前注冊了?2?個回調,它們會按順序被觸發 hook.call('China',?'Shenzhen',?'VJ')hook.tap('event-3',?(contry,?city,?people)?=>?{console.log('event-3:',?contry,?city,?people) })hook.tap('event-4',?(contry,?city,?people)?=>?{console.log('event-4:',?contry,?city,?people) })//?執行訂閱事件回調 //?鉤子上目前注冊了?4?個回調,它們會按順序被觸發 hook.call('USA',?'NYC',?'Trump')/******?下方為輸出?******/ event-1:?China?Shenzhen?VJ event-2:?China?Shenzhen?VJ event-1:?USA?NYC?Trump event-2:?USA?NYC?Trump event-3:?USA?NYC?Trump event-4:?USA?NYC?Trump這里順便說一下,tap 在英文中有“竊聽”的意思,用它作為訂閱事件的方法名,還挺形象和俏皮。
2.2 代碼實現
2.2.1 SyncHook.js
SyncHook 模塊的源碼(簡略版)如下:
/**?@file?SyncHook.js?**/const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncHookCodeFactory?extends?HookCodeFactory?{content({?onError,?onDone,?rethrowIfPossible?})?{return?this.callTapsSeries({onError:?(i,?err)?=>?onError(err),onDone,rethrowIfPossible});} }const?factory?=?new?SyncHookCodeFactory();const?COMPILE?=?function(options)?{factory.setup(this,?options);return?factory.create(options); };function?SyncHook(args?=?[],?name?=?undefined)?{const?hook?=?new?Hook(args,?name);hook.compile?=?COMPILE;return?hook; }module.exports?=?SyncHook;這段代碼理解起來還是很輕松的,SyncHook 實例化后其實就是一個 Hook 類的實例對象,并帶上了一個自定義的 compile 方法。顧名思義,可以猜測 compile 方法是最終調用 call 時所執行的接口。
我們先不分析 compile 的實現,就帶著對它的猜想,來看看 Hook 類的實現。
2.2.2 Hook 類
/**?@file?Hook.js?**/const?CALL_DELEGATE?=?function(...args)?{this.call?=?this._createCall("sync");return?this.call(...args); };class?Hook?{constructor(args?=?[],?name?=?undefined)?{this._args?=?args;this.name?=?name;this.taps?=?[];this.call?=?CALL_DELEGATE;??//?call?方法this._call?=?CALL_DELEGATE;}_createCall(type)?{return?this.compile({taps:?this.taps,args:?this._args,type:?type});}_tap(type,?options,?fn)?{if?(typeof?options?===?"string")?{options?=?{name:?options.trim()};}options?=?Object.assign({?type,?fn?},?options);this._insert(options);}tap(options,?fn)?{???//?tap?方法this._tap("sync",?options,?fn);}_resetCompilation()?{this.call?=?this._call;}_insert(item)?{this._resetCompilation();let?i?=?this.taps.length;this.taps[i]?=?item;} }為了方便閱讀,上方我只保留了 SyncHook 鉤子相關的代碼。這里需要知道的是,其中帶下劃線的方法如 _tap、_resetCompilation、_insert 等都屬于各鉤子公用的內部方法,而像 tap、call 方法是 SyncHook 鉤子專有的方法。
我們綜合梳理一下 SyncHook 調用 tap 和 call 的邏輯。
⑴ tap 的流程
繼續以前方示例代碼為例子:
hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap 的執行流程大致如下:
它會先在 _tap 方法里構建配置項 options 對象:
//?options?格式 {?type:?'sync',?fn:?callbackFunction,?name:?'event-1'?}再將 options 傳遞給 _insert 方法,該方法做了兩件事:
調用 this._resetCompilation() 重置 this.call;
發布訂閱模式的常規操作,提供一個數組(this.taps)用于訂閱收集,把 options 放入該數組。
之所以需要重置 this.call 方法,是因為 this.call 執行時會重寫自己:
this.call?=?function?CALL_DELEGATE(...args)?{this.call?=?this._createCall("sync");??//?overwrite?this.callreturn?this.call(...args); };所以為了讓 hook.tap 之后可以正常調用 hook.call,需要重新賦值 this.call,避免它被調用一次就不能再正常執行了。
⑵ call 的流程
this.call 一開始就重寫了自己:
this.call?=?this._createCall("sync");通過 this._createCall 的實現可以知道,this.call 被重寫為 this.compile 的返回值:
_createCall(type)?{return?this.compile({taps:?this.taps,interceptors:?this.interceptors,args:?this._args,type:?type});}這也驗證了前面對于 compile 的猜想 —— SyncHook.js 中定義的 compile 方法是在 call 調用時執行的。我們回過頭來看它的實現:
/**?@file?SyncHook.js?**/const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncHookCodeFactory?extends?HookCodeFactory?{content({?onError,?onDone,?rethrowIfPossible?})?{return?this.callTapsSeries({onError:?(i,?err)?=>?onError(err),onDone,rethrowIfPossible});} }const?factory?=?new?SyncHookCodeFactory();//?compile?方法 const?COMPILE?=?function(options)?{factory.setup(this,?options);return?factory.create(options); };compile 定義的方法中分別調用了 SyncHookCodeFactory 實例的 setup 和 create 方法,它們都是從父類 HookCodeFactory 繼承過來的。
2.2.3 HookCodeFactory 類
HookCodeFactory 的內容相對較多,不過沒關系,我們暫時只看當前 hook.call 執行流程相關的代碼段即可:
/****?@file?HookCodeFactory.js?****/class?HookCodeFactory?{constructor(config)?{this.config?=?config;this.options?=?undefined;this._args?=?undefined;}setup(instance,?options)?{instance._x?=?options.taps.map(t?=>?t.fn);??//?注冊的事件回調數組}create(options)?{this.init(options);let?fn;switch?(this.options.type)?{case?"sync":fn?=?new?Function(this.args(),'"use?strict";\n'?+this.content({??//?content?是在?SyncHook.js?中定義的onError:?err?=>?`throw?${err};\n`,onResult:?result?=>?`return?${result};\n`,resultReturns:?true,onDone:?()?=>?"",}));break;}this.deinit();return?fn;}init(options)?{??//?方便在?HookCodeFactory?內部獲取?options?和用戶入參this.options?=?options;this._args?=?options.args.slice();}deinit()?{??//?移除?init?的處理this.options?=?undefined;this._args?=?undefined;}args()?{??//?返回參數字符串let?allArgs?=?this._args;if?(allArgs.length?===?0)?{return?"";}?else?{return?allArgs.join(",?");}} }可以看到 setup 方法會將當前已注冊事件的回調統一放到數組 this._x 中,后續要觸發所有訂閱事件回調,只需要按順序執行 this._x 即可。
而 create 則通過 new Function(args, functionString) 構造了一個函數,該函數最終由被重寫的 call 觸發。
所以這里我們只需要再確認下 this.content 方法執行后的返回值,就能知道最終 call 方法所執行的函數是什么。
回看前面的代碼,content 是在 SyncHook.js 中定義的:
/****?@file?SyncHook.js?****/class?SyncHookCodeFactory?extends?HookCodeFactory?{content({?onDone?})?{return?this.callTapsSeries({??//?實際上是?this.callTapsSeries?的調用onDone});} }順藤摸瓜,我們回 HookCodeFactory.js 接著看 this.callTapsSeries 的實現:
/****?@file?HookCodeFactory.js?****/callTapsSeries({onDone,})?{if?(this.options.taps.length?===?0)?return?onDone();let?code?=?"";let?current?=?onDone;??//?()?=>?''//?倒序遍歷for?(let?j?=?this.options.taps.length?-?1;?j?>=?0;?j--)?{const?content?=?this.callTap(j,?{onDone:?current,});current?=?()?=>?content;}code?+=?current();return?code;}callTap(tapIndex,?{?onDone?})?{let?code?=?"";let?hasTapCached?=?false;code?+=?`var?_fn${tapIndex}?=?_x[${tapIndex}];\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{case?"sync":code?+=?`_fn${tapIndex}(${this.args()});\n`;if?(onDone)?{//?onDone()?會返回上一次存儲的?codecode?+=?onDone();}break;}return?code;}callTap 方法每次執行會生成和返回單個訂閱事件執行代碼字符串,例如:
var?_fn0?=?_x[0]; _fn0(contry,?city,?people);callTapsSeries 會遍歷訂閱數組并逐次調用 callTap,最后將全部訂閱事件的執行代碼字符串拼接起來。
理解 callTapsSeries 方法的關鍵點,是理解 current 變量在每次迭代前后的變化。
假設存在 4 個訂閱事件,則 current 的變化如下:
| 第 1 次 | 3 | onDone,即 ()=>"" | () => "_x[3]代碼段" |
| 第 2 次 | 2 | () => "_x[3]代碼段" | () => "_x[2]代碼段 + _x[3]代碼段" |
| 第 3 次 | 1 | () => "_x[2]代碼段 + _x[3]代碼段" | () => "_x[1]代碼段 + _x[2]代碼段 + _x[3]代碼段" |
| 第 4 次 | 0 | () => "_x[1]代碼段 + _x[2]代碼段 + _x[3]代碼段" | () => "_x[0]代碼段 + _x[1]代碼段 + _x[2]代碼段 + _x[3]代碼段" |
因此最后直接拼接 content() 就能得到完整的代碼字符串。
順便我們也可以知道,onDone 參數是為了在遍歷開始時,作為 current 的默認值使用的。
示例:
每次用戶調用 syncHook.call 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 const?hook?=?new?SyncHook(["contry",?"city",?"people"]);hook.tap('event-1',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-2',?(contry,?city,?people)?=>?{//?略... })hook.call('China',?'Shenzhen',?'VJ')// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; _fn0(contry,?city,?people); var?_fn1?=?_x[1]; _fn1(contry,?city,?people);最終在 create 方法中通過 new Function 創建為常規函數供 call 調用:
function(contry,?city,?people )?{"use?strict";var?_x?=?this._x;var?_fn0?=?_x[0];_fn0(contry,?city,?people);var?_fn1?=?_x[1];_fn1(contry,?city,?people); }執行后, this._x 里的事件回調會按順序逐個執行。
三、SyncBailHook 的基礎實現
3.1 介紹
SyncBailHook 也是一個同步鉤子,不同于 SyncHook 的地方是,如果某個訂閱事件的回調函數返回了非 undefined 的值,那么會中斷該鉤子后續其它訂閱回調的調用:
const?{?SyncBailHook?}?=?require('tapable');//?初始化鉤子 const?hook?=?new?SyncBailHook(["contry",?"city",?"people"]);//?訂閱事件 hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap('event-2',?(contry,?city,?people)?=>?{console.log('event-2:',?contry,?city,?people);return?null;??//?設置了非?undefined?的返回值 })//?因為?event-2?設置了返回值,所以后續的?event-3、event-4?都不會執行 hook.tap('event-3',?(contry,?city,?people)?=>?{console.log('event-3:',?contry,?city,?people) })hook.tap('event-4',?(contry,?city,?people)?=>?{console.log('event-4:',?contry,?city,?people) })//?執行訂閱回調 hook.call('USA',?'NYC',?'Trump')/******?下方為輸出?******/ event-1:?USA?NYC?Trump event-2:?USA?NYC?Trump在上方示例中,因為 event-2 的回調返回了 null,故中斷了后續其它訂閱回調的執行。
3.2 代碼實現
SyncBailHook 的入口模塊為 SyncBailHook.js,它相對于前一節的 SyncHook.js 而言,只是多了一個 content/callTapsSeries 方法的 onResult 傳參:
/****?@file?SyncBailHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncBailHookCodeFactory?extends?HookCodeFactory?{content({?onDone,?onResult?})?{??//?新增?onResultreturn?this.callTapsSeries({onDone,??//?()?=>?''//?新增?onResultonResult:?(i,?result,?next)?=>`if(${result}?!==?undefined)?{\n${onResult(result)};\n}?else?{\n${next()}}\n`,});} }//?...略function?SyncBailHook(args?=?[],?name?=?undefined)?{//?...略 }module.exports?=?SyncBailHook;onXXXX 都是模板參數,它們執行后都會返回模板字符串,用于在 callTap 方法里拼接函數代碼段。
我們需要在調用 this.content 和 this.callTapsSeries 的地方分別做點修改,讓它們利用這個新增的模板參數,來實現 SyncBailHook 的功能。
⑴ content 調用處的改動
/****?@file?HookCodeFactory.js?****/create(options)?{this.init(options);let?fn;switch?(this.options.type)?{case?"sync":fn?=?new?Function(this.args(),'"use?strict";\n'?+this.header()?+this.content({onDone:?()?=>?"",//?新增屬性onResult:?result?=>?`return?${result};\n`,}));break;}this.deinit();return?fn;}這里的實現,其實等同于 SyncBailHookCodeFactory 調用 content 時不傳 onResult 的簡易處理:
class?SyncBailHookCodeFactory?extends?HookCodeFactory?{content({?onDone?})?{??//?注意這里不傳?onResult?了return?this.callTapsSeries({onDone,??//??()?=>?""onResult:?(i,?result,?next)?=>`if(${result}?!==?undefined)?{\nreturn?result;\n}?else?{\n${next()}}\n`,});} }⑵ this.callTapsSeries 調用處的改動
在 2.2.3 小節末尾,我們知道 this.callTapsSeries 中最關鍵的實現,是利用了 current 的變化和傳遞,來實現各訂閱事件回調執行代碼字符串的拼接。
對于 SyncBailHook 的需求,我們可以利用 onResult 把 current() 的模板包起來(把 onResult 的第三個參數設為 current 即可):
/****?@file?HookCodeFactory.js?****/callTapsSeries({onDone,onResult?//?新增})?{if?(this.options.taps.length?===?0)?return?onDone();let?code?=?"";let?current?=?onDone;for?(let?j?=?this.options.taps.length?-?1;?j?>=?0;?j--)?{const?content?=?this.callTap(j,?{onDone:?!onResult?&&?current,??//?如果存在?onResult?則設為?false//?新增?onResult?傳參,把?current?包起來onResult:onResult?&&(result?=>?{return?onResult(j,?result,?current);}),});current?=?()?=>?content;}code?+=?current();return?code;}callTap(tapIndex,?{?onDone,?onResult?})?{??//?新增?onResult?參數let?code?=?"";code?+=?`var?_fn${tapIndex}?=?_x[${tapIndex}];\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{case?"sync":if?(onResult)?{??//?新增code?+=?`var?_result${tapIndex}?=?_fn${tapIndex}(${this.args()});\n`;}?else?{code?+=?`_fn${tapIndex}(${this.args()});\n`;}if?(onResult)?{??//?新增code?+=?onResult(`_result${tapIndex}`);}//?對?SyncBailHook?來說?onDone=falseif?(onDone)?{code?+=?onDone();}break;}return?code;}這樣每次執行 callTap 時,我們都能獲得如下模板:
//?假設?I?為遍歷索引 var?_fnI?=?_x[I]; var?_resultI?=?_fnI(...args); if(_resultI?!==?undefined)?{return?_resultI; }?else?{[current()?返回的模板,即前一次迭代生成的代碼段] }示例
每次用戶調用 syncBailHook.call 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 const?hook?=?new?SyncBailHook(["contry",?"city",?"people"]);hook.tap('event-1',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-2',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-3',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-4',?(contry,?city,?people)?=>?{//?略... })hook.call('USA',?'NYC',?'Trump')// callTapsSeries 生成的函數片段字符串:var?_fn0?=?_x[0];var?_result0?=?_fn0(contry,?city,?people);if?(_result0?!==?undefined)?{return?_result0;;}?else?{var?_fn1?=?_x[1];var?_result1?=?_fn1(contry,?city,?people);if?(_result1?!==?undefined)?{return?_result1;;}?else?{var?_fn2?=?_x[2];var?_result2?=?_fn2(contry,?city,?people);if?(_result2?!==?undefined)?{return?_result2;;}?else?{var?_fn3?=?_x[3];var?_result3?=?_fn3(contry,?city,?people);if?(_result3?!==?undefined)?{return?_result3;;}?else?{}}}}四、SyncWaterfallHook
4.1 介紹
SyncWaterfallHook 依舊為同步鉤子,不過它會把前一個訂閱回調所返回的內容,作為第一個參數傳遞給后續的訂閱回調:
const?SyncWaterfallHook?=?require('./SyncWaterfallHook.js');const?hook?=?new?SyncWaterfallHook(["contry",?"city",?"people"]);hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap('event-2',?(contry,?city,?people)?=>?{console.log('event-2:',?contry,?city,?people);return?'The?United?State';??//?設置了返回值 })hook.tap('event-3',?(contry,?city,?people)?=>?{console.log('event-3:',?contry,?city,?people) })hook.tap('event-4',?(contry,?city,?people)?=>?{console.log('event-4:',?contry,?city,?people) })hook.call('USA',?'NYC',?'Trump')/******?下方為輸出?******/ event-1:?USA?NYC?Trump event-2:?USA?NYC?Trump event-3:?The?United?State?NYC?Trump event-4:?The?United?State?NYC?Trump4.2 代碼實現
通過前面兩節,我們知道了讓訂閱事件回調按鉤子邏輯來執行的原理,不外乎是通過傳入 onXXXX 的模板參數,來生成 hook.call 最終調用的函數代碼。
SyncWaterfallHook 的實現也非常簡單,只需要調整 onDone 和 onResult 兩個模板參數即可:
/****?@file?SyncWaterfallHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncWaterfallHookCodeFactory?extends?HookCodeFactory?{content({?onResult?})?{return?this.callTapsSeries({onResult:?(i,?result,?next)?=>?{??//?修改點let?code?=?"";code?+=?`if(${result}?!==?undefined)?{\n`;code?+=?`${this._args[0]}?=?${result};\n`;code?+=?`}\n`;code?+=?next();return?code;},onDone:?()?=>?onResult(this._args[0]),??//?修改點});} }//?...略function?SyncWaterfallHook(args?=?[],?name?=?undefined)?{//?...略 }module.exports?=?SyncWaterfallHook;onDone 為訂閱對象數組遍歷時的初始化模板函數,執行后會生成 return ${this._args[0]};\n 字符串。
onResult 為訂閱對象數組遍歷時的非初始化模板函數,會判斷上一個訂閱回調返回值是否非 undefined,是則將 syncWaterfallHook.call 的第一個參數改為此返回值,再拼接上一次遍歷生成的模板內容。
示例
每次用戶調用 syncWaterfallHook.call 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 const?SyncWaterfallHook?=?require('./SyncWaterfallHook.js');const?hook?=?new?SyncWaterfallHook(["contry",?"city",?"people"]);hook.tap('event-1',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-2',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-3',?(contry,?city,?people)?=>?{//?略... })hook.tap('event-4',?(contry,?city,?people)?=>?{//?略... })hook.call('USA',?'NYC',?'Trump')// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; var?_result0?=?_fn0(contry,?city,?people); if(_result0?!==?undefined)?{contry?=?_result0; } var?_fn1?=?_x[1]; var?_result1?=?_fn1(contry,?city,?people); if(_result1?!==?undefined)?{contry?=?_result1; } var?_fn2?=?_x[2]; var?_result2?=?_fn2(contry,?city,?people); if(_result2?!==?undefined)?{contry?=?_result2; } var?_fn3?=?_x[3]; var?_result3?=?_fn3(contry,?city,?people); if(_result3?!==?undefined)?{contry?=?_result3; } return?contry;五、SyncLoopHook
5.1 介紹
這是最后一個同步鉤子了,SyncLoopHook 表示如果存在某個訂閱事件回調返回了非 undefined 的值,則全部訂閱事件回調從頭執行:
const?hook?=?new?SyncLoopHook([]); let?count?=?1;hook.tap('event-1',?()?=>?{console.log('event-1') })hook.tap('event-2',?()?=>?{console.log('event-2,?count:',?count);if?(count++?!==?3)?{return?true;} })hook.tap('event-3',?()?=>?{console.log('event-3'); })hook.call()/******?下方為輸出?******/ event-1 event-2,?count:?1 event-1 event-2,?count:?2 event-1 event-2,?count:?3 event-35.2 代碼實現
SyncLoopHook “從頭執行全部回調”的邏輯比較特殊,舊的方法已經無法滿足該需求,所以 Tapable 為其新開了一個 callTapsLooping 方法來處理:
/****?@file?SyncLoopHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncLoopHookCodeFactory?extends?HookCodeFactory?{content({?onDone?})?{//?this.callTapsLooping?為新增方法return?this.callTapsLooping({onDone});} }//?略...function?SyncLoopHook(args?=?[],?name?=?undefined)?{//?略... }module.exports?=?SyncLoopHook;我們看下 callTapsLooping 方法的實現:
/****?@file?HookCodeFactory.js?****///?新增?callTapsLooping?方法callTapsLooping({onDone,})?{if?(this.options.taps.length?===?0)?return?onDone();let?code?=?"";code?+=?"var?_loop;\n";code?+=?"do?{\n";code?+=?"_loop?=?false;\n";code?+=?this.callTapsSeries({onResult:?(i,?result,?next)?=>?{let?code?=?"";code?+=?`if(${result}?!==?undefined)?{\n`;code?+=?"_loop?=?true;\n";code?+=?`}?else?{\n`;code?+=?next();code?+=?`}\n`;return?code;},onDone,??//?()?=>?''});code?+=?"}?while(_loop);\n";return?code;}可以看到,callTapsLooping 在模板的外層包了個 do while 循環:
var?_loop; do?{_loop?=?false;${?callTapsSeries?生成的模板?} }?while(_loop)這里的后續邏輯很好猜測:callTapsSeries 生成的模板,只需要判斷訂閱回調返回值是否為 undefined,然后修改 _loop 即可。
而 callTapsLooping 傳入 callTapsSeries 的 onResult 參數完善了此塊邏輯:
示例
每次用戶調用 syncLoopHook.call 時,callTapsLooping 生成的函數片段字符串:
//?外部調用 const?SyncLoopHook?=?require('./SyncLoopHook.js'); const?hook?=?new?SyncLoopHook([]); let?count?=?1;hook.tap('event-1',?()?=>?{//?略... })hook.tap('event-2',?()?=>?{//?略... })hook.tap('event-3',?()?=>?{//?略... })hook.call()// callTapsLooping 生成的函數片段字符串: var?_loop; do?{_loop?=?false;var?_fn0?=?_x[0];var?_result0?=?_fn0();if?(_result0?!==?undefined)?{_loop?=?true;}?else?{var?_fn1?=?_x[1];var?_result1?=?_fn1();if?(_result1?!==?undefined)?{_loop?=?true;}?else?{var?_fn2?=?_x[2];var?_result2?=?_fn2();if?(_result2?!==?undefined)?{_loop?=?true;}?else?{}}} }?while?(_loop);六、AsyncSeriesHook
6.1 介紹
我們已經介紹完了 Tapable 的同步鉤子,接下來逐個介紹 Tapable 中異步相關的幾個鉤子,首先介紹最簡單的 AsyncSeriesHook。
AsyncSeriesHook 表示一個異步串行的鉤子,可以通過 hook.tapAsync 或 hook.tapPromise 方法,來注冊異步的事件回調。
這些訂閱事件的回調依舊是逐個執行,即必須等到上一個異步回調通知鉤子它已經執行完畢了,才能開始下一個異步回調:
//?初始化異步串行鉤子 const?hook?=?new?AsyncSeriesHook(['passenger']);//?使用?tapAsync?訂閱事件 hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(callback,?2000); })//?使用?tapPromise?訂閱事件 hook.tapPromise('Back?to?Shenzhen',?(passenger)?=>?{console.log(`${passenger}?is?now?comming?back?to?Shenzhen...`);return?new?Promise((resolve)?=>?{setTimeout(resolve,?3000);}); })//?執行訂閱回調 hook.callAsync('VJ',?()?=>?{?console.log('Done!')?});console.log('Starts?here...');/******?下方為輸出?******/ VJ?is?on?the?way?to?Beijing... Starts?here... VJ?is?now?comming?back?to?Shenzhen... Done!對于使用 hook.tapAsync 來訂閱事件的異步回調,可以通過執行最后一個參數來通知鉤子“我已經執行完畢,可以接著執行后面的回調了”;
對于使用 hook.tapPromise 來訂閱事件的異步回調,需要返回一個 Promise,當其狀態為 resolve 時,鉤子才會開始執行后續其它訂閱回調。
另外需要留意下,AsyncSeriesHook 鉤子使用新的 hook.callAsync 來執行訂閱回調(而不再是 hook.call),且支持傳入回調(最后一個參數),在全部訂閱事件執行完畢后觸發。
6.2 代碼實現
首先是 AsyncSeriesHook 模塊的代碼,結構和 SyncHook 是基本一樣的:
/****?@file?AsyncSeriesHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncSeriesHookCodeFactory?extends?HookCodeFactory?{content({?onDone,?onError?})?{??//?新增?onErrorreturn?this.callTapsSeries({//?新增?onError,處理異步回調中的錯誤onError:?(i,?err,?next,?doneBreak)?=>?onError(err)?+?doneBreak(true),onDone});} }//?略...function?AsyncSeriesHook(args?=?[],?name?=?undefined)?{//?略... }module.exports?=?AsyncSeriesHook;這里我們新增了 onError 方法來處理異步回調中的錯誤。
AsyncSeriesHook 鉤子實現的關鍵點,是對其幾個專用方法 hook.tapAsync、hook.tapPromise 和 hook.callAsync 的實現,我們先到 Hook.js 中查看它們的定義:
/****?@file?Hook.js?****/ const?CALL_DELEGATE?=?function?(...args)?{this.call?=?this._createCall("sync");return?this.call(...args); };//?新增 const?CALL_ASYNC_DELEGATE?=?function(...args)?{this.callAsync?=?this._createCall("async");return?this.callAsync(...args); };class?Hook?{constructor(args?=?[],?name?=?undefined)?{this._args?=?args;this.name?=?name;this.taps?=?[];this.call?=?CALL_DELEGATE;this._call?=?CALL_DELEGATE;this._callAsync?=?CALL_ASYNC_DELEGATE;??//?新增this.callAsync?=?CALL_ASYNC_DELEGATE;??//?新增}tap(options,?fn)?{this._tap("sync",?options,?fn);}//?新增?tapAsynctapAsync(options,?fn)?{this._tap("async",?options,?fn);}//?新增?tapPromisetapPromise(options,?fn)?{this._tap("promise",?options,?fn);}_resetCompilation()?{this.call?=?this._call;this.callAsync?=?this._callAsync;??//?新增}//?...略 }module.exports?=?Hook;可以看到這幾個新增的方法所調用的接口跟之前的 hoo.tap、hook.call 一致,只是把訂閱對象信息的 type 標記為 async/promise 罷了。
我們繼續到 HookCodeFactory 查閱 hook.callAsync 的處理:
/****?@file?HookCodeFactory.js?****/ class?HookCodeFactory?{//?...略create(options)?{this.init(options);let?fn;switch?(this.options.type)?{case?"sync":fn?=?new?Function(this.args(),'"use?strict";\n'?+this.header()?+this.content({onDone:?()?=>?"",onResult:?result?=>?`return?${result};\n`,}));break;//?新增?async?類型處理(hook.callAsync)case?"async":fn?=?new?Function(this.args({after:?"_callback"}),'"use?strict";\n'?+this.header()?+this.content({onError:?err?=>?`_callback(${err});\n`,onResult:?result?=>?`_callback(null,?${result});\n`,onDone:?()?=>?"_callback();\n"}));break;}this.deinit();return?fn;}callTapsSeries({onDone,onResult,onError,?//?新增?onError})?{//?...略for?(let?j?=?this.options.taps.length?-?1;?j?>=?0;?j--)?{const?content?=?this.callTap(j,?{onError:?error?=>?onError(j,?error,?current,?doneBreak),??//?新增?onError//?...略});//?...略}//?...略return?code;}args({?before,?after?}?=?{})?{??//?新增?before,?after?參數let?allArgs?=?this._args;if?(before)?allArgs?=?[before].concat(allArgs);??//?新增if?(after)?allArgs?=?allArgs.concat(after);??//?新增if?(allArgs.length?===?0)?{return?"";}?else?{return?allArgs.join(",?");}} }如同 hook.call 一樣,hook.callAsync 執行時,先調用的是 create 方法里 case "async" 的代碼塊。
從傳入 this.content 的參數可以猜測到,hook.callAsync 的函數模板里,會使用 Node Error First 異步回調的格式來書寫相應邏輯:
function?callback(err,?nextAsyncFunc)?{if?(err)?{//?錯誤處理}?else?{nextAsyncFunc?&&?nextAsyncFunc(callback)} };另外留意 this.args 方法的改動 —— 在返回用戶入參字符串的同時,可以通過傳入 before/after,往返回的字符串前后再多插一個自定義參數。這也是為何 hook.callAsync 相較同步鉤子的 hook.call,可以多傳入一個可執行的回調參數的原因。
我們接著看 callTap 方法里新增的對 tapAsync 和 tapPromise 訂閱回調的模板處理邏輯。
⑴ 生成 tapAsync 訂閱回調模板
/****?@file?HookCodeFactory.js?****/ class?HookCodeFactory?{//?...略callTap(tapIndex,?{?onError,?onResult,?onDone?})?{let?code?+=?`var?_fn${tapIndex}?=?${this.getTapFn(tapIndex)};\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{case?"sync"://?...略//?新增?async?類型處理(通過?hook.tapAsync?訂閱的回調模板處理)case?"async":let?cbCode?=?`(function(_err${tapIndex})?{\n`;cbCode?+=?`if(_err${tapIndex})?{\n`;cbCode?+=?onError(`_err${tapIndex}`);cbCode?+=?"}?else?{\n";if?(onDone)?{cbCode?+=?onDone();}cbCode?+=?"}\n";cbCode?+=?"})";code?+=?`_fn${tapIndex}(${this.args({after:?cbCode})});\n`;break;}} }該代碼段會生成如下模板:
//?假設遍歷索引?tapIndex?為?I var?_fnI?=?_x[I]; _fnI(passenger,?function(_errI)?{if(_errI)?{_callback(_errI);}?else?{${?前一次遍歷的模板?}} });即生成了一個 Error First 的異步回調嵌套模板。
留意模板中的 _callback 是最終在 create 方法中,通過 new Function 時傳入的形參,代表用戶傳入 hook.callAsync 的回調參數(最后一個參數,在報錯或全部訂閱事件結束時候觸發):
fn?=?new?Function(this.args({after:?"_callback"}),this.header()?+?this.content(...) );示例
用戶調用 asyncSeriesHook.call 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 const?hook?=?new?AsyncSeriesHook(['passenger']);hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(callback,?1000); })hook.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Shanghai...`);setTimeout(callback,?2000); })hook.callAsync('VJ',?()?=>?{});// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; _fn0(passenger,?(function?(_err0)?{if?(_err0)?{_callback(_err0);}?else?{var?_fn1?=?_x[1];_fn1(passenger,?(function?(_err1)?{if?(_err1)?{_callback(_err1);}?else?{_callback();}}));} }));⑵ 生成 tapPromise 訂閱回調模板
分析完 hook.tapAsync 方式訂閱的回調的模板生成方式,我們來看下 hook.tapPromise 是如何生成模板的:
/****?@file?HookCodeFactory.js?****/ class?HookCodeFactory?{//?...略callTap(tapIndex,?{?onError,?onResult,?onDone?})?{let?code?+=?`var?_fn${tapIndex}?=?${this.getTapFn(tapIndex)};\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{case?"sync"://?...略case?"async"://?...略//?新增?async?類型處理(通過?hook.tapPromise?訂閱的回調模板處理)case?"promise":code?+=?`var?_hasResult${tapIndex}?=?false;\n`;code?+=?`var?_promise${tapIndex}?=?_fn${tapIndex}(${this.args()});\n`;code?+=?`if?(!_promise${tapIndex}?||?!_promise${tapIndex}.then)\n`;code?+=?`??throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise${tapIndex}?+?')');\n`;code?+=?`_promise${tapIndex}.then((function(_result${tapIndex})?{\n`;code?+=?`_hasResult${tapIndex}?=?true;\n`;if?(onDone)?{code?+=?onDone();}code?+=?`}),?function(_err${tapIndex})?{\n`;code?+=?`if(_hasResult${tapIndex})?throw?_err${tapIndex};\n`;code?+=?onError(`_err${tapIndex}`);code?+=?"});\n";break;}} }該代碼段會生成如下模板:
//?假設遍歷索引?tapIndex?為?I var?_fnI?=?_x[I]; var?_hasResultI?=?false; var?_promiseI?=?_fnI(passenger); if?(!_promiseI?||?!_promiseI.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promiseI?+?')'); _promise1.then((function?(_resultI)?{_hasResultI?=?true;${?上一次遍歷生成的模板?} }),?function?(_errI)?{if?(_hasResultI)?throw?_errI;_callback(_errI); });該模板利用了 Promise.then 的能力來決定下一個訂閱回調的執行時機:
示例
用戶調用 asyncSeriesHook.callAsync 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 const?hook?=?new?AsyncSeriesHook(['passenger']);hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{//?略... })hook.tapPromise('Back?to?Shenzhen',?(passenger)?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; var?_hasResult0?=?false; var?_promise0?=?_fn0(passenger); if?(!_promise0?||?!_promise0.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise0?+?')'); _promise0.then((function?(_result0)?{_hasResult0?=?true;var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1(passenger);if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;_callback();}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;_callback(_err1);}); }),?function?(_err0)?{if?(_hasResult0)?throw?_err0;_callback(_err0); });七、AsyncSeriesBailHook
7.1 介紹
AsyncSeriesBailHook 和 AsyncSeriesHook 的表現基本一致,不過會判斷訂閱事件回調的返回值是否為 undefined,如果非 undefined 會中斷后續訂閱回調的執行:
const?hook1?=?new?AsyncSeriesBailHook(['passenger']);hook1.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(()?=>?{callback(true);??//?設置了返回值},?2000); })hook1.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Shanghai...`);setTimeout(callback,?2000); })hook1.callAsync('Jay',?()?=>?{?console.log('Hook1?has?been?Done!')?});const?hook2?=?new?AsyncSeriesBailHook(['passenger']);hook2.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{console.log(`${passenger}?is?taking?off?to?Tokyo...`);return?new?Promise((resolve)?=>?{setTimeout(()?=>?{resolve(true);??//?設置了返回值},?1000);}); })hook2.tapPromise('Back?to?Shenzhen',?(passenger)?=>?{console.log(`${passenger}?is?now?comming?back?to?Shenzhen...`);return?new?Promise((resolve)?=>?{setTimeout(resolve,?2000);}); })hook2.callAsync('VJ',?()?=>?{?console.log('Hook2?has?been?Done!')?});/******?下方為輸出?******/ Jay?is?on?the?way?to?Beijing... VJ?is?taking?off?to?Tokyo... Hook2?has?been?Done! Hook1?has?been?Done!7.2 代碼實現
回顧第三節 SyncBailHook 的實現我們可以得知,它相較 SyncHook 而言只是新增了一個 onResult 來進一步處理模板邏輯。
AsyncSeriesBailHook 的實現也是如此,只需要在 AsyncSeriesHook 的基礎上添加一個 onResult,對上一個訂閱回調返回值進行判斷即可:
/****?@file?AsyncSeriesBailHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncSeriesBailHookCodeFactory?extends?HookCodeFactory?{content({?onDone,?onError,?onResult?})?{??//?新增?onResultreturn?this.callTapsSeries({onError:?(i,?err,?next,?doneBreak)?=>?onError(err)?+?doneBreak(true),//?新增?onResultonResult:?(i,?result,?next)?=>`if(${result}?!==?undefined)?{\n${onResult(result)}\n}?else?{\n${next()}}\n`,onDone});} }//?...略function?AsyncSeriesBailHook(args?=?[],?name?=?undefined)?{//?...略 }module.exports?=?AsyncSeriesBailHook;然后是模板拼接處的修改:
/****?@file?HookCodeFactory.js?****/callTap(tapIndex,?{?onError,?onDone,?onResult?})?{//?備注?-?這里 onResult 傳進來后的值為://?result?=>?`if(${result}?!==?undefined)?{\n${onResult(result)}\n}?else?{\n${next()}}\n`let?code?=?"";code?+=?`var?_fn${tapIndex}?=?${this.getTapFn(tapIndex)};\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{case?"sync"://?...略case?"async":let?cbCode?=?"";if?(onResult)??//?新增cbCode?+=?`(function(_err${tapIndex},?_result${tapIndex})?{\n`;else?cbCode?+=?`(function(_err${tapIndex})?{\n`;cbCode?+=?`if(_err${tapIndex})?{\n`;cbCode?+=?onError(`_err${tapIndex}`);cbCode?+=?"}?else?{\n";if?(onResult)?{??//?新增cbCode?+=?onResult(`_result${tapIndex}`);}if?(onDone)?{cbCode?+=?onDone();}cbCode?+=?"}\n";cbCode?+=?"})";code?+=?`_fn${tapIndex}(${this.args({after:?cbCode})});\n`;break;case?"promise":code?+=?`var?_hasResult${tapIndex}?=?false;\n`;code?+=?`var?_promise${tapIndex}?=?_fn${tapIndex}(${this.args()});\n`;code?+=?`if?(!_promise${tapIndex}?||?!_promise${tapIndex}.then)\n`;code?+=?`??throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise${tapIndex}?+?')');\n`;code?+=?`_promise${tapIndex}.then((function(_result${tapIndex})?{\n`;code?+=?`_hasResult${tapIndex}?=?true;\n`;if?(onResult)?{??//?新增code?+=?onResult(`_result${tapIndex}`);}if?(onDone)?{code?+=?onDone();}code?+=?`}),?function(_err${tapIndex})?{\n`;code?+=?`if(_hasResult${tapIndex})?throw?_err${tapIndex};\n`;code?+=?onError(`_err${tapIndex}`);code?+=?"});\n";break;}return?code;}我們在下方的示例中,看看模板發生了哪些改動。
示例
用戶調用 asyncSeriesBailHook.callAsync 時,callTapsSeries 生成的函數片段字符串:
⑴ hook.tapAsync 訂閱回調對應模板:
//?外部調用 const?AsyncSeriesBailHook?=?require('./AsyncSeriesBailHook.js');const?hook1?=?new?AsyncSeriesBailHook(['passenger']);hook1.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook1.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{//?略... })hook1.callAsync('Jay',?()?=>?{});// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; _fn0(passenger,?function?(_err0,?_result0)?{??//?新增?_result0if?(_err0)?{_callback(_err0);}?else?{if?(_result0?!==?undefined)?{??//?新增判斷_callback(null,?_result0);}?else?{var?_fn1?=?_x[1];_fn1(passenger,?function?(_err1,?_result1)?{??//?新增?_result1if?(_err1)?{_callback(_err1);}?else?{if?(_result1?!==?undefined)?{??//?新增判斷_callback(null,?_result1);}?else?{_callback();}}});}} });⑵ hook.tapPromise 訂閱回調對應模板:
//?外部調用 const?hook2?=?new?AsyncSeriesBailHook(['passenger']);hook2.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{console.log(`${passenger}?is?taking?off?to?Tokyo...`);return?new?Promise((resolve)?=>?{setTimeout(()?=>?{resolve(true);??//?設置了返回值},?1000);}); })hook2.tapPromise('Back?to?Shenzhen',?(passenger)?=>?{console.log(`${passenger}?is?now?comming?back?to?Shenzhen...`);return?new?Promise((resolve)?=>?{setTimeout(resolve,?2000);}); })hook2.callAsync('VJ',?()?=>?{?console.log('Hook2?has?been?Done!')?});// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; var?_hasResult0?=?false; var?_promise0?=?_fn0(passenger); if?(!_promise0?||?!_promise0.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise0?+?')'); _promise0.then((function?(_result0)?{_hasResult0?=?true;if?(_result0?!==?undefined)?{??//?新增判斷_callback(null,?_result0);}?else?{var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1(passenger);if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;if?(_result1?!==?undefined)?{??//?新增判斷_callback(null,?_result1);}?else?{_callback();}}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;_callback(_err1);});} }),?function?(_err0)?{if?(_hasResult0)?throw?_err0;_callback(_err0); });具體變更點見代碼中的注釋。
Tapable 中的模板拼接乍一看挺復雜,但它的實現,肯定是先思考最終成型的模板應該長怎樣,再根據需求在 callTap 方法中添加對應邏輯。因此,通過最終的模板來反推功能的實現,也是一種理解 Tapable 源碼的方式。
八、AsyncSeriesWaterfallHook
8.1 介紹
AsyncSeriesWaterfallHook 也是異步串行的鉤子,不過在執行時,上一個訂閱回調的返回值會傳遞給下一個訂閱回調,并覆蓋掉新訂閱回調的第一個參數:
const?hook?=?new?AsyncSeriesWaterfallHook(['passenger']);hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);callback(null,?2000);??//?這里要留意使用?Error?First?的寫法 })hook.tapPromise('Fly?to?Tokyo',?(time)?=>?{console.log(`Take?off?to?Tokyo?after?${time}?ms.`);return?new?Promise((resolve)?=>?{setTimeout(()?=>?{resolve(1000);},?time);}); })hook.tapAsync('Fly?to?Shanghai',?(time,?callback)?=>?{console.log(`Take?off?to?Shanghai?after?${time}?ms.`);setTimeout(callback,?time); })hook.callAsync('VJ',?()?=>?{?console.log('Hook?has?been?Done!')?});8.2 代碼實現
和 4.2 小節 SyncWaterfallHook 的實現一樣,AsyncSeriesWaterfallHook 可以通過修改 onResult 和 onDone 方式來實現:
/****?@file?AsyncSeriesWaterfallHook.js?****/const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncSeriesWaterfallHookCodeFactory?extends?HookCodeFactory?{content({?onDone,?onError,?onResult?})?{return?this.callTapsSeries({onError:?(i,?err,?next,?doneBreak)?=>?onError(err)?+?doneBreak(true),//?修改?onResultonResult:?(i,?result,?next)?=>?{let?code?=?"";code?+=?`if(${result}?!==?undefined)?{\n`;code?+=?`${this._args[0]}?=?${result};\n`;code?+=?`}\n`;code?+=?next();return?code;},//?修改?onResultonDone:?()?=>?onResult(this._args[0])});} }//?...略module.exports?=?AsyncSeriesWaterfallHook;示例
用戶調用 asyncSeriesWaterfallHook.callAsync 時,callTapsSeries 生成的函數片段字符串:
//?外部調用 hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook.tapPromise('Fly?to?Tokyo',?(time)?=>?{//?略... })hook.tapAsync('Fly?to?Shanghai',?(time,?callback)?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// callTapsSeries 生成的函數片段字符串: var?_fn0?=?_x[0]; _fn0(passenger,?(function?(_err0,?_result0)?{if?(_err0)?{_callback(_err0);}?else?{if?(_result0?!==?undefined)?{??//?新增passenger?=?_result0;}var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1(passenger);if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;if?(_result1?!==?undefined)?{??//?新增passenger?=?_result1;}var?_fn2?=?_x[2];_fn2(passenger,?(function?(_err2,?_result2)?{if?(_err2)?{_callback(_err2);}?else?{if?(_result2?!==?undefined)?{??//?新增passenger?=?_result2;}_callback(null,?passenger);}}));}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;_callback(_err1);});} }));九、AsyncParallelHook
9.1 介紹
AsyncParallelHook 是一個異步并行的鉤子,全部訂閱回調都會同時并行觸發:
const?hook?=?new?AsyncParallelHook(['passenger']);hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(()?=>?{console.log('[Beijing]?Arrived');callback()},?2000); })hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{console.log(`${passenger}?is?on?the?way?to?Tokyo...`);return?new?Promise((resolve)?=>?{setTimeout(()?=>?{console.log('[Tokyo]?Arrived');resolve();},?1000);}); })hook.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Shanghai...`);callback() })hook.callAsync('VJ',?()?=>?{?console.log('Hook?has?been?Done!')?});/******?下方為輸出?******/ VJ?is?on?the?way?to?Beijing... VJ?is?on?the?way?to?Tokyo... VJ?is?on?the?way?to?Shanghai... [Tokyo]?Arrived [Beijing]?Arrived Hook?has?been?Done!9.2 代碼實現
如同 SyncsLoopHook 鉤子需要新增 this.callTapsLooping 方法,在 this.callTapsSeries 外頭多套一層模板來實現具體需求。
這次的 AsyncParallelHook 鉤子也需要新增一個 this.callTapsParallel 方法實現并行能力,但會摒棄串行的 this.callTapsSeries 接口,改而直接調用 callTap:
/****?@file?AsyncParallelHook.js?****/const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncParallelHookCodeFactory?extends?HookCodeFactory?{content({?onError,?onDone?})?{//?新增?this.callTapsParallel?方法return?this.callTapsParallel({onError:?(i,?err,?done,?doneBreak)?=>?onError(err)?+?doneBreak(true),onDone});} }//?...略module.exports?=?AsyncParallelHook;this.callTapsParallel 的具體實現:
/****?@file?HookCodeFactory.js?****/callTapsParallel({onError,onResult,onDone })?{if?(this.options.taps.length?<=?1)?{return?this.callTapsSeries({onError,onResult,onDone});}let?code?=?"";code?+=?"do?{\n";code?+=?`var?_counter?=?${this.options.taps.length};\n`;if?(onDone)?{code?+=?"var?_done?=?(function()?{\n";code?+=?onDone();code?+=?"});\n";}for?(let?i?=?0;?i?<?this.options.taps.length;?i++)?{const?done?=?()?=>?{if?(onDone)?return?"if(--_counter?===?0)?_done();\n";else?return?"--_counter;";};const?doneBreak?=?skipDone?=>?{if?(skipDone?||?!onDone)?return?"_counter?=?0;\n";else?return?"_counter?=?0;\n_done();\n";};code?+=?"if(_counter?<=?0)?break;\n";code?+=?this.callTap(i,?{onError:?error?=>?{let?code?=?"";code?+=?"if(_counter?>?0)?{\n";code?+=?onError(i,?error,?done,?doneBreak);code?+=?"}\n";return?code;},onResult:onResult?&&(result?=>?{let?code?=?"";code?+=?"if(_counter?>?0)?{\n";code?+=?onResult(i,?result,?done,?doneBreak);code?+=?"}\n";return?code;}),onDone:!onResult?&&(()?=>?{return?done();})});}code?+=?"}?while(false);\n";return?code; }callTapsParallel 新增的模板會遍歷訂閱對象,然后逐個扔給 callTap 生成單個訂閱回調的模板,再將它們拼接起來同步執行:
do?{??//?形成閉包,避免?const/let?變量提升到外部_fn0(...);_fn1(...);..._fnN(...); }?while(false)另外新增了計數器變量 _counter,初始化值為訂閱對象數量,每次執行完單個訂閱回調會自減一,訂閱回調可以通過它判斷自己是否最后一個回調(如果是則執行用戶傳入 hook.callAsync 的“事件終止”回調)。
示例
用戶調用 asyncSeriesHook.callAsync 時,callTapsParallel 生成的函數片段字符串:
//?外部調用 const?hook?=?new?AsyncParallelHook(['passenger']);hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{//?略... })hook.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// callTapsParallel 生成的函數片段字符串: do?{var?_counter?=?3;var?_done?=?(function?()?{_callback();});if?(_counter?<=?0)?break;var?_fn0?=?_x[0];_fn0(passenger,?(function?(_err0)?{if?(_err0)?{if?(_counter?>?0)?{_callback(_err0);_counter?=?0;}}?else?{if?(--_counter?===?0)?_done();}}));if?(_counter?<=?0)?break;var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1(passenger);if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;if?(--_counter?===?0)?_done();}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;if?(_counter?>?0)?{_callback(_err1);_counter?=?0;}});if?(_counter?<=?0)?break;var?_fn2?=?_x[2];_fn2(passenger,?(function?(_err2)?{if?(_err2)?{if?(_counter?>?0)?{_callback(_err2);_counter?=?0;}}?else?{if?(--_counter?===?0)?_done();}})); }?while?(false);十、AsyncParallelBailHook
10.1 介紹
AsyncParallelBailHook 和 AsyncParallelHook 基本一致,但如果前一個訂閱回調返回了非 undefined 的值,會中斷后續其它訂閱回調的執行,并觸發用戶傳入 hook.callAsync 的“事件終止”回調:
hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);//?注意這里不走異步處理,直接調用?callbackcallback(null,?true) })hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{//?執行前發現上個訂閱回調返回了?true,故不會執行console.log(`${passenger}?is?on?the?way?to?Tokyo...`);return?new?Promise((resolve)?=>?{console.log('[Tokyo]?Arrived');resolve(true);}); })hook.callAsync('VJ',?()?=>?{?console.log('Hook?has?been?Done!')?});/******?下方為輸出?******/ VJ??is?on?the?way?to?Beijing... Hook?has?been?Done!如果一個異步的訂閱回調會返回非 undefined 的值,但在它返回前,其它并行執行的訂閱回調會照常執行不受影響。這種情況唯一受影響的,是“事件終止”回調的執行位置:
const?hook?=?new?AsyncParallelBailHook(['passenger']);hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(()?=>?{console.log('[Beijing]?Arrived');callback(null,?true)},?500); })hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{console.log(`${passenger}?is?on?the?way?to?Tokyo...`);return?new?Promise((resolve)?=>?{setTimeout(()?=>?{console.log('[Tokyo]?Arrived');resolve(true);},?2000);}); })hook.tapAsync('Fly?to?Shanghai',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Shanghai...`);setTimeout(()?=>?{console.log('[Shanghai]?Arrived');callback()},?1000); })hook.callAsync('VJ',?()?=>?{?console.log('Hook?has?been?Done!')?});/******?下方為輸出?******/ VJ?is?on?the?way?to?Beijing... VJ?is?on?the?way?to?Tokyo... VJ?is?on?the?way?to?Shanghai... [Beijing]?Arrived Hook?has?been?Done!??//?“事件終止”回調打印的內容 [Shanghai]?Arrived [Tokyo]?Arrived可以看到“事件終止”回調會在 Fly to Beijing 訂閱回調結束后觸發,因為該訂閱回調返回了 true。另外因為該回調是異步的,所以其它的訂閱回調會照常被并發執行。
10.2 代碼實現
AsyncParallelBailHook 的實現比較粗暴直接,是在 AsyncParallelBailHook.js 里定義 content 的方法中,在模板前面新增一段內容:
/****?@file?AsyncParallelBailHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncParallelBailHookCodeFactory?extends?HookCodeFactory?{content({?onError,?onResult,?onDone?})?{let?code?=?"";code?+=?`var?_results?=?new?Array(${this.options.taps.length});\n`;code?+=?"var?_checkDone?=?function()?{\n";code?+=?"for(var?i?=?0;?i?<?_results.length;?i++)?{\n";code?+=?"var?item?=?_results[i];\n";code?+=?"if(item?===?undefined)?return?false;\n";code?+=?"if(item.result?!==?undefined)?{\n";code?+=?onResult("item.result");code?+=?"return?true;\n";code?+=?"}\n";code?+=?"if(item.error)?{\n";code?+=?onError("item.error");code?+=?"return?true;\n";code?+=?"}\n";code?+=?"}\n";code?+=?"return?false;\n";code?+=?"}\n";code?+=?this.callTapsParallel({onError:?(i,?err,?done,?doneBreak)?=>?{let?code?=?"";code?+=?`if(${i}?<?_results.length?&&?((_results.length?=?${i?+1}),?(_results[${i}]?=?{?error:?${err}?}),?_checkDone()))?{\n`;code?+=?doneBreak(true);code?+=?"}?else?{\n";code?+=?done();code?+=?"}\n";return?code;},onResult:?(i,?result,?done,?doneBreak)?=>?{let?code?=?"";code?+=?`if(${i}?<?_results.length?&&?(${result}?!==?undefined?&&?(_results.length?=?${i?+1}),?(_results[${i}]?=?{?result:?${result}?}),?_checkDone()))?{\n`;code?+=?doneBreak(true);code?+=?"}?else?{\n";code?+=?done();code?+=?"}\n";return?code;},onTap:?(i,?run,?done,?doneBreak)?=>?{let?code?=?"";if?(i?>?0)?{code?+=?`if(${i}?>=?_results.length)?{\n`;code?+=?done();code?+=?"}?else?{\n";}code?+=?run();if?(i?>?0)?code?+=?"}\n";return?code;},onDone});return?code;} }//?...略 module.exports?=?AsyncParallelBailHook;留意這里的 onTap 參數,它可傳遞給 this.callTapsParallel 來靈活處理 callTap 方法生成的模板:
/****?@file?HookCodeFactory.js?****/ callTapsParallel({onError,onResult,onDone,onTap?=?(i,?run)?=>?run()??//?新增 })?{//?略...for?(let?i?=?0;?i?<?this.options.taps.length;?i++)?{//?略...//?新增改動,調用?this.callTap?的地方使用?onTap?包起來code?+=?onTap(i,()?=>this.callTap(i,?{//?略...}),done,doneBreak);}//?略...return?code; }content 方法為模板新增了一個 _results 數組用于存儲訂閱回調的執行信息(返回值和錯誤);還新增一個 _checkDone 方法,通過遍歷 _results 來檢查事件是否應該結束 —— 若發現某個訂閱回調執行出錯,或者返回了非 undefined 值,_checkDone 方法會返回 true 并執行用戶傳入的“事件終止”回調)。
每個訂閱回調執行后,會把其執行信息寫入 _results 數組并執行 _checkDone()。
示例
用戶調用 asyncParallelBailHook.callAsync 時,content 方法生成的函數片段字符串:
//?外部調用 hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook.tapPromise('Fly?to?Tokyo',?()?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// content 方法生成的函數片段字符串: var?_results?=?new?Array(2); var?_checkDone?=?function?()?{for?(var?i?=?0;?i?<?_results.length;?i++)?{var?item?=?_results[i];if?(item?===?undefined)?return?false;if?(item.result?!==?undefined)?{_callback(null,?item.result);return?true;}if?(item.error)?{_callback(item.error);return?true;}}return?false; } do?{var?_counter?=?2;var?_done?=?(function?()?{_callback();});if?(_counter?<=?0)?break;var?_fn0?=?_x[0];_fn0(passenger,?(function?(_err0,?_result0)?{if?(_err0)?{if?(_counter?>?0)?{if?(0?<?_results.length?&&?((_results.length?=?1),?(_results[0]?=?{?error:?_err0?}),?_checkDone()))?{_counter?=?0;}?else?{if?(--_counter?===?0)?_done();}}}?else?{if?(_counter?>?0)?{if?(0?<?_results.length?&&?(_result0?!==?undefined?&&?(_results.length?=?1),?(_results[0]?=?{?result:?_result0?}),?_checkDone()))?{_counter?=?0;}?else?{if?(--_counter?===?0)?_done();}}}}));if?(_counter?<=?0)?break;if?(1?>=?_results.length)?{if?(--_counter?===?0)?_done();}?else?{var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1(passenger);if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;if?(_counter?>?0)?{if?(1?<?_results.length?&&?(_result1?!==?undefined?&&?(_results.length?=?2),?(_results[1]?=?{?result:?_result1?}),?_checkDone()))?{_counter?=?0;}?else?{if?(--_counter?===?0)?_done();}}}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;if?(_counter?>?0)?{if?(1?<?_results.length?&&?((_results.length?=?2),?(_results[1]?=?{?error:?_err1?}),?_checkDone()))?{_counter?=?0;}?else?{if?(--_counter?===?0)?_done();}}});} }?while?(false);十一、AsyncSeriesLoopHook
11.1 介紹
AsyncSeriesLoopHook 是 Tapable 不對外暴露的隱藏鉤子,但它并不神秘 —— 它和第 5 節所介紹的 SyncLoopHook 的表現一致,訂閱回調都是按順序串行執行的(前一個訂閱回調執行完了才會開始執行下一個回調),若有回調返回了非 undefined 的值,會中斷進度從頭開始整個流程。區別只是在 AsyncSeriesLoopHook 里被執行的訂閱回調是異步的:
const?hook?=?new?AsyncSeriesLoopHook([]);let?count?=?1;hook.tapAsync('event-1',?(callback)?=>?{console.log('event-1?starts...');setTimeout(()?=>?{console.log('event-1?done');callback()},?500); })hook.tapPromise('event-2',?()?=>?{return?new?Promise((resolve)?=>?{console.log('event-2?starts...');setTimeout(()?=>?{console.log('event-2?done,?count:',?count);if?(count++?!==?3)?{resolve(true)}?else?{resolve()}},?1000);}); })hook.tapAsync('event-3',?(callback)?=>?{console.log('event-3?starts...');setTimeout(()?=>?{console.log('event-3?done');callback()},?2000); })hook.callAsync(()?=>?{?console.log('Hook?has?been?Done!')?});/******?下方為輸出?******/ event-1?starts... event-1?done event-2?starts... event-2?done,?count:?1 event-1?starts... event-1?done event-2?starts... event-2?done,?count:?2 event-1?starts... event-1?done event-2?starts... event-2?done,?count:?3 event-3?starts... event-3?done Hook?has?been?Done!11.2 代碼實現
AsyncSeriesLoopHook 模塊和 SyncLoopHook 模塊基本是一樣的,都使用了 this.callTapsLooping 接口來實現串行執行、循環執行的能力:
/****?@file?AsyncSeriesLoopHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncSeriesLoopHookCodeFactory?extends?HookCodeFactory?{content({?onError,?onDone?})?{return?this.callTapsLooping({onError:?(i,?err,?next,?doneBreak)?=>?onError(err)?+?doneBreak(true),onDone});} }//?略...module.exports?=?AsyncSeriesLoopHook;但目前 this.callTapsLooping 接口只能處理同步的訂閱回調,為了讓其可以處理異步的訂閱回調,需要加一點改動:
/****?@file?HookCodeFactory.js?****/ callTapsLooping({?onError,?onDone?})?{??//?新增?onErrorif?(this.options.taps.length?===?0)?return?onDone();const?syncOnly?=?this.options.taps.every(t?=>?t.type?===?"sync");??//?新增let?code?=?"";if?(!syncOnly)?{??//?新增code?+=?"var?_looper?=?(function()?{\n";code?+=?"var?_loopAsync?=?false;\n";}code?+=?"var?_loop;\n";code?+=?"do?{\n";code?+=?"_loop?=?false;\n";code?+=?this.callTapsSeries({onError,onResult:?(i,?result,?next,?doneBreak)?=>?{let?code?=?"";code?+=?`if(${result}?!==?undefined)?{\n`;code?+=?"_loop?=?true;\n";if?(!syncOnly)?code?+=?"if(_loopAsync)?_looper();\n";??//?新增code?+=?doneBreak(true);code?+=?`}?else?{\n`;code?+=?next();code?+=?`}\n`;return?code;},onDone});code?+=?"}?while(_loop);\n";if?(!syncOnly)?{??//?新增code?+=?"_loopAsync?=?true;\n";code?+=?"});\n";code?+=?"_looper();\n";}return?code; }這里的改動相當于在最外層包了一個 _looper 函數方便在異步的訂閱回調返回了非 undefined 的時候,來遞歸調用自己實現循環。
SyncLoopHook 的那套 do-while 只適合同步的訂閱回調,因為如果遇上異步的訂閱回調,等它執行完畢時 do-while 已經執行結束了,無法再循環。
示例
用戶調用 asyncSeriesLoopHook.callAsync 時,callTapsLooping 生成的函數片段字符串:
//?外部調用? const?hook?=?new?AsyncSeriesLoopHook([]);hook.tapAsync('event-1',?(callback)?=>?{//?略... })hook.tapPromise('event-2',?()?=>?{//?略... })hook.tapAsync('event-3',?(callback)?=>?{//?略... })hook.callAsync(()?=>?{?console.log('Hook?has?been?Done!')?});// callTapsLooping 生成的函數片段字符串:var?_looper?=?(function?()?{var?_loopAsync?=?false;var?_loop;do?{_loop?=?false;var?_fn0?=?_x[0];_fn0((function?(_err0,?_result0)?{if?(_err0)?{_callback(_err0);}?else?{if?(_result0?!==?undefined)?{_loop?=?true;??//?沒有意義,因為回調是異步的,while?已經結束了if?(_loopAsync)?_looper();??//?需要調用?_looper?來重新執行}?else?{var?_fn1?=?_x[1];var?_hasResult1?=?false;var?_promise1?=?_fn1();if?(!_promise1?||?!_promise1.then)throw?new?Error('Tap?function?(tapPromise)?did?not?return?promise?(returned?'?+?_promise1?+?')');_promise1.then((function?(_result1)?{_hasResult1?=?true;if?(_result1?!==?undefined)?{_loop?=?true;if?(_loopAsync)?_looper();}?else?{_callback();}}),?function?(_err1)?{if?(_hasResult1)?throw?_err1;_callback(_err1);});}}}));}?while?(_loop);_loopAsync?=?true; }); _looper();十二、攔截器
12.1 介紹
終于介紹完了 Tappable 的全部鉤子的基礎實現,我們可以開始考慮提升一下鉤子的更多能力,首先讓鉤子們支持攔截的功能。
Tappable 中的所有鉤子都支持設置攔截器,可以在鉤子執行的各階段進行攔截。主要的攔截接口有如下幾個:
register:訂閱前觸發攔截,調用 hook.intercept 方法時執行攔截回調。當前鉤子有多少個訂閱事件就會執行多少次 register 攔截回調,可以在該攔截回調里修改訂閱者信息。
call:用戶調用 hook.call/callAsync 時觸發,在訂閱事件的回調執行前執行,參數為用戶傳參。只會觸發一次。
loop:loop 類型鉤子每次循環起始時觸發(排在 call 攔截器后面),參數為用戶傳參。循環幾次就會觸發幾次。
tap:調用 hook.call/callAsync 時觸發,在訂閱事件的回調執行前執行(排在 call 和 loop 攔截器后面),參數為訂閱者信息。有多個訂閱回調就會執行多次。
error:調用 hook.call/callAsync 時觸發,攔截時機為執行訂閱回調出錯時,參數為錯誤對象。
done:調用 hook.call/callAsync 時觸發,攔截時機為全部訂閱回調執行完畢的時候(排在用戶傳入的“事件終止”回調前面),沒有參數。
攔截器示例 - 同步訂閱回調:
const?{?SyncHook?}?=?require('tapable');//?初始化同步鉤子 const?hook?=?new?SyncHook(["contry",?"city",?"people"]);//?設置攔截器 hook.intercept({//?訂閱前觸發register:?(options)?=>?{console.log(`[register-intercept]?${options.name}?is?going?registering...`);//?修改訂閱者信息if?(options.name?===?'event-2')?{options.name?=?'event-intercepted';options.fn?=?(contry,?city,?people)?=>?{console.log('event-intercepted:',?contry,?city,?people)};}return?options;??//?訂閱者的信息會變成修改后的},//?call?方法調用時觸發call:?(...args)?=>?{console.log('[call-intercept]',?args);},//?調用訂閱事件回調前觸發tap:?(options)?=>?{console.log('[tap-intercept]',?options);}, });//?注冊事件 hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap('event-2',?(contry,?city,?people)?=>?{console.log('event-2:',?contry,?city,?people) })//?執行事件 hook.call('China',?'Shenzhen',?'VJ')/******?下方為輸出?******/ [register-intercept]?event-1?is?going?registering... [register-intercept]?event-2?is?going?registering... [call-intercept]?[?'China',?'Shenzhen',?'VJ'?] [tap-intercept]?{?type:?'sync',?fn:?[Function?(anonymous)],?name:?'event-1'?} event-1:?China?Shenzhen?VJ [tap-intercept]?{?type:?'sync',?fn:?[Function?(anonymous)],?name:?'event-intercepted'?} event-intercepted:?China?Shenzhen?VJ Hook?is?done.攔截器示例 - 異步訂閱回調:
const?hook?=?new?AsyncSeriesLoopHook(['name',?'country']);hook.intercept({//?訂閱前觸發register:?(options)?=>?{console.log(`[register-intercept]?${options.name}?is?going?registering...`);//?修改訂閱者信息if?(options.name?===?'event-1')?{const?oldFn?=?options.fn;options.fn?=?(...args)?=>?{args[1]?=?'USA';oldFn(...args);}}return?options;??//?訂閱者的信息會變成修改后的},//?call?方法調用時觸發call(...args)?{console.log('[call-intercept]',?args);},//?調用訂閱事件回調前觸發tap(options)?{console.log('[tap-intercept]',?options);},loop(...args)?{console.log('[loop-intercept]',?args);},done()?{console.log('[done-intercept]?Last?interceptor.')} });let?count?=?1;hook.tapAsync('event-1',?(name,?country,?callback)?=>?{console.log(`event-1?starts...,?the?country?of?${name}?is?${country}.`);setTimeout(()?=>?{console.log('event-1?done');callback()},?500); })hook.tapPromise('event-2',?()?=>?{return?new?Promise((resolve)?=>?{console.log('event-2?starts...');setTimeout(()?=>?{console.log('event-2?done,?count:',?count);if?(count++?!==?2)?{resolve(true)}?else?{resolve()}},?1000);}); })hook.tapAsync('event-3',?(name,?country,?callback)?=>?{console.log('event-3?starts...');setTimeout(()?=>?{console.log('event-3?done');callback()},?2000); })hook.callAsync('Trump',?'China',?()?=>?{?console.log('Hook?has?been?done!');?});/******?下方為輸出?******/ [register-intercept]?event-1?is?going?registering... [register-intercept]?event-2?is?going?registering... [register-intercept]?event-3?is?going?registering... [call-intercept]?[?'Trump',?'China'?] [loop-intercept]?[?'Trump',?'China'?] [tap-intercept]?{?type:?'async',?fn:?[Function?(anonymous)],?name:?'event-1'?} event-1?starts...,?the?country?of?Trump?is?USA. event-1?done [tap-intercept]?{?type:?'promise',?fn:?[Function?(anonymous)],?name:?'event-2'?} event-2?starts... event-2?done,?count:?1 [loop-intercept]?[?'Trump',?'China'?] [tap-intercept]?{?type:?'async',?fn:?[Function?(anonymous)],?name:?'event-1'?} event-1?starts...,?the?country?of?Trump?is?USA. event-1?done [tap-intercept]?{?type:?'promise',?fn:?[Function?(anonymous)],?name:?'event-2'?} event-2?starts... event-2?done,?count:?2 [tap-intercept]?{?type:?'async',?fn:?[Function?(anonymous)],?name:?'event-3'?} event-3?starts... event-3?done [done-intercept]?Last?interceptor. Hook?has?been?done!攔截器還支持多個配置,會依次執行:
const?hook?=?new?AsyncSeriesLoopHook(['name',?'country']);//?配置第一個攔截器 hook.intercept({register:?(options)?=>?{console.log(`[register-intercept-1]?${options.name}?is?going?registering...`);return?options;},tap()?{console.log('[tap-intercept-1]');},done()?{console.log('[done-intercept-1]?Last?interceptor.')} });//?配置第二個攔截器 hook.intercept({register:?(options)?=>?{console.log(`[register-intercept-2]?${options.name}?is?going?registering...`);return?options;},tap()?{console.log('[tap-intercept-2]');},done()?{console.log('[done-intercept-2]?Last?interceptor.')} });hook.tapAsync('event-1',?(name,?country,?callback)?=>?{console.log(`event-1?starts...,?the?country?of?${name}?is?${country}.`);setTimeout(()?=>?{console.log('event-1?done');callback()},?500); })hook.tapAsync('event-2',?(name,?country,?callback)?=>?{console.log('event-2?starts...');setTimeout(()?=>?{console.log('event-2?done');callback()},?1000); })hook.callAsync('VJ',?'China',?()?=>?{?console.log('Hook?has?been?done!');?});/******?下方為輸出?******/ [register-intercept-1]?event-1?is?going?registering... [register-intercept-2]?event-1?is?going?registering... [register-intercept-1]?event-2?is?going?registering... [register-intercept-2]?event-2?is?going?registering... [tap-intercept-1] [tap-intercept-2] event-1?starts...,?the?country?of?VJ?is?China. event-1?done [tap-intercept-1] [tap-intercept-2] event-2?starts... event-2?done [done-intercept-1]?Last?interceptor. [done-intercept-2]?Last?interceptor. Hook?has?been?done!攔截器是個很有意思的功能,是各工具“生命周期”的底層鉤子,我們來看下 Tapable 中是如何實現攔截器的。
12.2 代碼實現
12.2.1 intercept 入口和 register 攔截器
首先要實現的自然是 hook.intercept 的接口,我們需要回到 Hook.js 中添加該方法,并新增一個數組來存放攔截器配置:
/****?@file?Hook.js?****/ class?Hook?{constructor(args?=?[],?name?=?undefined)?{this._args?=?args;this.name?=?name;this.taps?=?[];this.interceptors?=?[];??//?新增,用于存放攔截器this.call?=?CALL_DELEGATE;this._call?=?CALL_DELEGATE;this._callAsync?=?CALL_ASYNC_DELEGATE;this.callAsync?=?CALL_ASYNC_DELEGATE;}_createCall(type)?{return?this.compile({taps:?this.taps,args:?this._args,type:?type,interceptors:?this.interceptors??//?新增,傳遞給?HookCodeFactory});}intercept(interceptor)?{??//?新增?intercept?接口this._resetCompilation();this.interceptors.push(Object.assign({},?interceptor));if?(interceptor.register)?{for?(let?i?=?0;?i?<?this.taps.length;?i++)?{//?執行?register?攔截器,用返回值替換訂閱對象信息this.taps[i]?=?interceptor.register(this.taps[i]);}}} }在用戶注冊攔截器的時候(調用 hook.intercept),會將攔截器配置對象存入數組 this.interceptors,然后遍歷訂閱事件對象,逐個觸發 register 攔截器,并用攔截回調的返回值來替換訂閱對象信息。這也是為何我們可以在 register 攔截階段直接修改訂閱對象信息。
12.2.2 call、error、done 攔截器
我們都知道 Tapable 是通過模板拼接來完成其全部能力的,攔截器的實現方式也不例外。
試想一下,我們可以通過存儲于 this.interceptors 的數組里獲取到攔截器配置,自然也可以在需要攔截的地方,將 this.interceptors[n].interceptorName() 字符串嵌入模板對應位置,最終執行模板函數時,就會在適當的時間點執行對應的攔截回調。
例如在 HookCodeFactory.js 中,我們可以新增一個 contentWithInterceptors 方法,在調用 this.content 前觸發 ?call 攔截器,并修改傳入 this.content 的 onError 和 onDone 模板,讓它們在執行時分別先觸發 error 攔截器和 done 攔截器:
/****?@file?HookCodeFactory.js?****/contentWithInterceptors(options)?{if?(this.options.interceptors.length?>?0)?{const?onError?=?options.onError;const?onResult?=?options.onResult;const?onDone?=?options.onDone;let?code?=?"";for?(let?i?=?0;?i?<?this.options.interceptors.length;?i++)?{const?interceptor?=?this.options.interceptors[i];if?(interceptor.call)?{code?+=?`${this.getInterceptor(i)}.call(${this.args()});\n`;}}code?+=?this.content(Object.assign(options,?{onError:onError?&&(err?=>?{let?code?=?"";for?(let?i?=?0;?i?<?this.options.interceptors.length;?i++)?{const?interceptor?=?this.options.interceptors[i];if?(interceptor.error)?{code?+=?`${this.getInterceptor(i)}.error(${err});\n`;}}code?+=?onError(err);return?code;}),onResult,onDone:onDone?&&(()?=>?{let?code?=?"";for?(let?i?=?0;?i?<?this.options.interceptors.length;?i++)?{const?interceptor?=?this.options.interceptors[i];if?(interceptor.done)?{code?+=?`${this.getInterceptor(i)}.done();\n`;}}code?+=?onDone();return?code;})}));return?code;}?else?{return?this.content(options);} } getInterceptor(idx)?{return?`_interceptors[${idx}]`; }將 create 方法中調用 content 的地方改為 contentWithInterceptors:
/****?@file?HookCodeFactory.js?****/ create(options)?{this.init(options);let?fn;switch?(this.options.type)?{case?"sync":fn?=?new?Function(this.args(),'"use?strict";\n'?+this.header()?+this.contentWithInterceptors({??//?修改onDone:?()?=>?"",onResult:?result?=>?`return?${result};\n`,}));break;case?"async":fn?=?new?Function(this.args({after:?"_callback"}),'"use?strict";\n'?+this.header()?+this.contentWithInterceptors({??//?修改onError:?err?=>?`_callback(${err});\n`,onResult:?result?=>?`_callback(null,?${result});\n`,onDone:?()?=>?"_callback();\n"}));break;}this.deinit();return?fn; }header()?{let?code?=?"";code?+=?"var?_x?=?this._x;\n";if?(this.options.interceptors.length?>?0)?{??//?新增code?+=?"var?_taps?=?this.taps;\n";code?+=?"var?_interceptors?=?this.interceptors;\n";}return?code; }12.2.3 tap 攔截器
tap 攔截器是在 callTap 開始執行時觸發的,它的實現很簡單:
/****?@file?HookCodeFactory.js?****/ callTap(tapIndex,?{?onError,?onDone,?onResult?})?{let?code?=?"";let?hasTapCached?=?false;??//?新增for?(let?i?=?0;?i?<?this.options.interceptors.length;?i++)?{??//?新增const?interceptor?=?this.options.interceptors[i];if?(interceptor.tap)?{if?(!hasTapCached)?{code?+=?`var?_tap${tapIndex}?=?${this.getTap(tapIndex)};\n`;hasTapCached?=?true;}code?+=?`${this.getInterceptor(i)}.tap(_tap${tapIndex});\n`;}}code?+=?`var?_fn${tapIndex}?=?${this.getTapFn(tapIndex)};\n`;const?tap?=?this.options.taps[tapIndex];switch?(tap.type)?{//?略...}return?code; }它會生成這樣的模板內容:
//?假設遍歷索引為?I,且有兩個攔截器配置對象 var?_tapI?=?tapOptionsI; _interceptors[0].tap(_tapI) _interceptors[1].tap(_tapI)12.2.4 loop 攔截器
loop 攔截器只需要在 callTapsLooping 的 do-while 模板開頭插入攔截代碼即可:
/****?@file?HookCodeFactory.js?****/ callTapsLooping({?onError,?onDone?})?{//?略...code?+=?"var?_loop;\n";code?+=?"do?{\n";code?+=?"_loop?=?false;\n";for?(let?i?=?0;?i?<?this.options.interceptors.length;?i++)?{??//?新增const?interceptor?=?this.options.interceptors[i];if?(interceptor.loop)?{code?+=?`${this.getInterceptor(i)}.loop(${this.args()});\n`;}}code?+=?this.callTapsSeries({...});//?略...return?code; }至此 Tapable 中的幾個攔截器就這么被實現了,沒想象中的復雜對吧?
十三、HookMap
13.1 介紹
HookMap 是 Tapable 的一個輔助類(helper),利用它可以更好地封裝我們的各種鉤子:
const?keyedHook?=?new?HookMap(key?=>?new?SyncHook(["desc"]));//?創建名為“webpack”的鉤子,并訂閱“Plugin-A”和“Plugin-B”事件 const?webpackHook?=?keyedHook.for("webpack"); webpackHook.tap("Plugin-A",?(desc)?=>?{?console.log("Plugin-A",?desc)?}); webpackHook.tap("Plugin-B",?(desc)?=>?{?console.log("Plugin-B",?desc)?});//?創建名為“babel”的鉤子,并訂閱“Plugin-C”事件 keyedHook.for("babel").tap("Plugin-C",?(desc)?=>?{?console.log("Plugin-C",?desc)?});function?getHook(hookName)?{//?獲取指定名稱的鉤子return?keyedHook.get(hookName); }function?callHook(hookName,?desc)?{const?hook?=?getHook(hookName);if(hook?!==?undefined)?{const?call?=?hook.call?||?hook.callAsync;call.bind(hook)(desc);} }callHook('webpack',?"It's?on?Webpack?plugins?processing")module.exports.getHook?=?getHook; module.exports.callHook?=?callHook;/******?下方為輸出? Plugin-A?It's?on?Webpack?plugins?processing Plugin-B?It's?on?Webpack?plugins?processing ******/13.2 代碼實現
HookMap 使用了 this._factory 來存儲用戶在初始化時傳入的鉤子構造函數(鉤子工廠),后續用戶調用 hookMap.for 時會通過該構造函數生成指定類型的鉤子,并以鉤子名稱為 key 存入一個 Map 對象,后續如果需要獲取該鉤子,從 Map 對象查找它的名稱即可:
/****?@file?HookMap.js?****/ const?util?=?require("util");class?HookMap?{constructor(factory,?name?=?undefined)?{this._map?=?new?Map();this.name?=?name;this._factory?=?factory;}get(key)?{return?this._map.get(key);}for(key)?{const?hook?=?this.get(key);if?(hook?!==?undefined)?{return?hook;??//?支持鏈式調用}let?newHook?=?this._factory(key);this._map.set(key,?newHook);return?newHook;??//?支持鏈式調用} }module.exports?=?HookMap;留意 for 的開頭會先判斷是否已經構建了該名稱的鉤子,如果是則直接返回。
我們就這樣完成了 HookMap 的基礎能力,可見它就是一個語法糖,實現相對簡單。
另外 HookMap 支持一個名為 factory 的攔截器,它可以修改 HookMap 的鉤子構造函數(this._factory),對新建的鉤子會生效:
const?keyedHook?=?new?HookMap(()?=>?new?SyncHook(["desc"]));keyedHook.for("webpack").tap("Plugin-A",?(desc)?=>?{?console.log("Plugin-A-phase-1",?desc)?});//?配置攔截器,更換新的鉤子類型 keyedHook.intercept({factory:?(key)?=>?{console.log(`[intercept]?New?hook:?${key}.`)return?new?SyncBailHook(["desc"]);} });//?已有名為?webpack?的鉤子,攔截器不會影響,它依舊是?SyncHook?鉤子 keyedHook.for("webpack").tap("Plugin-A",?(desc)?=>?{console.log("Plugin-A-phase-2",?desc);return?true; });keyedHook.for("webpack").tap("Plugin-B",?(desc)?=>?{console.log("Plugin-B",?desc); });//?新的鉤子,類型為攔截器替換掉的?SyncBailHook keyedHook.for("babel").tap("Plugin-C",?(desc)?=>?{console.log("Plugin-C-phase-1",?desc);return?true; });keyedHook.for("babel").tap("Plugin-C",?(desc)?=>?{console.log("Plugin-C-phase-2",?desc); });function?getHook(hookName)?{return?keyedHook.get(hookName); }function?callHook(hookName,?desc)?{const?hook?=?getHook(hookName);if?(hook?!==?undefined)?{const?call?=?hook.call?||?hook.callAsync;call.bind(hook)(desc);} }callHook('webpack',?"It's?on?Webpack?plugins?processing"); callHook('babel',?"It's?on?Webpack?plugins?processing");/******?下方為輸出? [intercept]?New?hook:?babel. Plugin-A-phase-1?It's?on?Webpack?plugins?processing Plugin-A-phase-2?It's?on?Webpack?plugins?processing Plugin-B?It's?on?Webpack?plugins?processing Plugin-C-phase-1?It's?on?Webpack?plugins?processing ******/它的實現也很簡單,這里不再贅述:
/****?@file?HookMap.js?****/ const?defaultFactory?=?(key,?hook)?=>?hook;class?HookMap?{constructor(factory,?name?=?undefined)?{this._map?=?new?Map();this.name?=?name;this._factory?=?factory;this._interceptors?=?[];??//?新增}get(key)?{return?this._map.get(key);}for(key)?{const?hook?=?this.get(key);if?(hook?!==?undefined)?{return?hook;??//?如果已有同名鉤子,攔截器不會生效}let?newHook?=?this._factory(key);//?新增const?interceptors?=?this._interceptors;//?新增for?(let?i?=?0;?i?<?interceptors.length;?i++)?{newHook?=?interceptors[i].factory(key,?newHook);}this._map.set(key,?newHook);return?newHook;}//?新增intercept(interceptor)?{this._interceptors.push(Object.assign({factory:?defaultFactory},interceptor));} }module.exports?=?HookMap;十四、MultiHook
這是最后一個要介紹的 Tapable 的模塊了,它也是一個語法糖,方便你批量操作多個鉤子:
const?MultiHook?=?require('./lib/MultiHook'); const?SyncHook?=?require('./lib/SyncHook'); const?SyncBailHook?=?require('./lib/SyncBailHook.js');const?hook1?=?new?SyncHook(["contry",?"city",?"people"]); const?hook2?=?new?SyncBailHook(["contry",?"city",?"people"]); const?hooks?=?new?MultiHook([hook1,?hook2]);hooks.tap('multiHook-event',?(contry,?city,?people)?=>?{console.log('multiHook-event-1:',?contry,?city,?people);return?true; })hooks.tap('multiHook-event',?(contry,?city,?people)?=>?{console.log('multiHook-event-2:',?contry,?city,?people);return?true; })hook1.call('China',?'Shenzhen',?'VJ'); hook2.call('USA',?'NYC',?'Joey');/******?下方為輸出? multiHook-event-1:?China?Shenzhen?VJ multiHook-event-2:?China?Shenzhen?VJ multiHook-event-1:?USA?NYC?Joey ******/其實現非常簡單,只是一個普通的封裝模塊,將傳入的鉤子們存在 this.hooks 中,在調用內部方法的時候通過 for of 來遍歷鉤子和執行對應接口:
/****?@file?HookMap.js?****/ class?MultiHook?{constructor(hooks,?name?=?undefined)?{this.hooks?=?hooks;this.name?=?name;}tap(options,?fn)?{for?(const?hook?of?this.hooks)?{hook.tap(options,?fn);}}tapAsync(options,?fn)?{for?(const?hook?of?this.hooks)?{hook.tapAsync(options,?fn);}}tapPromise(options,?fn)?{for?(const?hook?of?this.hooks)?{hook.tapPromise(options,?fn);}}intercept(interceptor)?{for?(const?hook?of?this.hooks)?{hook.intercept(interceptor);}} }module.exports?=?MultiHook;十五、小結
以上就是全部關于 Tapable 的分析了,從中我們了解到了 Tapable 的實現是基于模板的拼接,這是個很有創意的形式,有點像搭積木,把各鉤子的訂閱回調按相關邏輯一層層搭建成型,這其實不是很輕松的事情。
在掌握了 Tapable 各種鉤子、攔截器的執行流程和實現之后,也相信你會對 Webpack 的工作流程有了更進一步的了解,畢竟 Webpack 的工作流程不外乎就是將各個插件串聯起來,而 Tapable 幫忙實現了這一事件流機制。
另外這么長的文章應該存在一些錯別字或語病,歡迎大家評論指出,我再一一修改。
最后感謝大家能耐心讀完本文,希望你們能有所收獲,共勉~
總結
以上是生活随笔為你收集整理的【Webpack】1256- 硬核解析 Webpack 事件流核心!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6 模块化【暴露、引入、引入并暴露】
- 下一篇: 神经网络分类四种模型,神经网络分类特点区