【Webpack】1256- 硬核解析 Webpack 事件流核心!
一、Tapable 介紹
Tapable 是 Webpack 整個(gè)生命周期及其插件機(jī)制的事件流實(shí)現(xiàn),它提供了多種形式的發(fā)布訂閱模式的 API,我們可以利用它來(lái)注冊(cè)自定義事件,并在不同的時(shí)機(jī)去觸發(fā)。
Tapable 對(duì)外提供了如下幾種鉤子(Hooks):
const?{SyncHook,SyncBailHook,SyncWaterfallHook,SyncLoopHook,AsyncParallelHook,AsyncParallelBailHook,AsyncSeriesHook,AsyncSeriesBailHook,AsyncSeriesWaterfallHook}?=?require("tapable");每個(gè)鉤子擁有自己專屬的事件執(zhí)行機(jī)制和觸發(fā)時(shí)機(jī),Webpack 正是利用它們,在不同的編譯階段來(lái)調(diào)用各插件回調(diào),從而影響編譯結(jié)果。
本文來(lái)自全棧修仙源碼交流群?VaJoy 大佬,他會(huì)逐步介紹每個(gè)鉤子,并分析其源碼實(shí)現(xiàn)。本文內(nèi)容偏硬核,建議讀者分時(shí)間耐心閱讀。
另外,本文各模塊的代碼放在 Github 上,推薦大家下載后配合本文一同食用,遇到不理解的地方可以打斷點(diǎn)調(diào)試,學(xué)起來(lái)會(huì)很快。
https://github.com/VaJoy/tapable-analysis
二、SyncHook 的基礎(chǔ)實(shí)現(xiàn)
2.1 介紹
SyncHook 是 Tapable 所提供的最簡(jiǎn)單的鉤子,它是一個(gè)同步鉤子。
本小節(jié)的內(nèi)容會(huì)比較長(zhǎng),因?yàn)闀?huì)介紹到很多鉤子們共用的方法。學(xué)習(xí)完 SyncHook 鉤子的實(shí)現(xiàn),再去分析其它鉤子的源碼會(huì)輕松很多。
初始化 SyncHook 后,可以通過(guò)調(diào)用實(shí)例的 tap 方法來(lái)注冊(cè)事件,調(diào)用 call 方法按注冊(cè)順序來(lái)執(zhí)行回調(diào):
//?初始化同步鉤子 const?hook?=?new?SyncHook(["contry",?"city",?"people"]);//?注冊(cè)/訂閱事件 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) })//?執(zhí)行訂閱事件回調(diào) //?鉤子上目前注冊(cè)了?2?個(gè)回調(diào),它們會(huì)按順序被觸發(fā) 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) })//?執(zhí)行訂閱事件回調(diào) //?鉤子上目前注冊(cè)了?4?個(gè)回調(diào),它們會(huì)按順序被觸發(fā) 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這里順便說(shuō)一下,tap 在英文中有“竊聽(tīng)”的意思,用它作為訂閱事件的方法名,還挺形象和俏皮。
2.2 代碼實(shí)現(xiàn)
2.2.1 SyncHook.js
SyncHook 模塊的源碼(簡(jiǎn)略版)如下:
/**?@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;這段代碼理解起來(lái)還是很輕松的,SyncHook 實(shí)例化后其實(shí)就是一個(gè) Hook 類的實(shí)例對(duì)象,并帶上了一個(gè)自定義的 compile 方法。顧名思義,可以猜測(cè) compile 方法是最終調(diào)用 call 時(shí)所執(zhí)行的接口。
我們先不分析 compile 的實(shí)現(xiàn),就帶著對(duì)它的猜想,來(lái)看看 Hook 類的實(shí)現(xiàn)。
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 鉤子相關(guān)的代碼。這里需要知道的是,其中帶下劃線的方法如 _tap、_resetCompilation、_insert 等都屬于各鉤子公用的內(nèi)部方法,而像 tap、call 方法是 SyncHook 鉤子專有的方法。
我們綜合梳理一下 SyncHook 調(diào)用 tap 和 call 的邏輯。
⑴ tap 的流程
繼續(xù)以前方示例代碼為例子:
hook.tap('event-1',?(contry,?city,?people)?=>?{console.log('event-1:',?contry,?city,?people) })hook.tap 的執(zhí)行流程大致如下:
它會(huì)先在 _tap 方法里構(gòu)建配置項(xiàng) options 對(duì)象:
//?options?格式 {?type:?'sync',?fn:?callbackFunction,?name:?'event-1'?}再將 options 傳遞給 _insert 方法,該方法做了兩件事:
調(diào)用 this._resetCompilation() 重置 this.call;
發(fā)布訂閱模式的常規(guī)操作,提供一個(gè)數(shù)組(this.taps)用于訂閱收集,把 options 放入該數(shù)組。
之所以需要重置 this.call 方法,是因?yàn)?this.call 執(zhí)行時(shí)會(huì)重寫(xiě)自己:
this.call?=?function?CALL_DELEGATE(...args)?{this.call?=?this._createCall("sync");??//?overwrite?this.callreturn?this.call(...args); };所以為了讓 hook.tap 之后可以正常調(diào)用 hook.call,需要重新賦值 this.call,避免它被調(diào)用一次就不能再正常執(zhí)行了。
⑵ call 的流程
this.call 一開(kāi)始就重寫(xiě)了自己:
this.call?=?this._createCall("sync");通過(guò) this._createCall 的實(shí)現(xiàn)可以知道,this.call 被重寫(xiě)為 this.compile 的返回值:
_createCall(type)?{return?this.compile({taps:?this.taps,interceptors:?this.interceptors,args:?this._args,type:?type});}這也驗(yàn)證了前面對(duì)于 compile 的猜想 —— SyncHook.js 中定義的 compile 方法是在 call 調(diào)用時(shí)執(zhí)行的。我們回過(guò)頭來(lái)看它的實(shí)現(xiàn):
/**?@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 定義的方法中分別調(diào)用了 SyncHookCodeFactory 實(shí)例的 setup 和 create 方法,它們都是從父類 HookCodeFactory 繼承過(guò)來(lái)的。
2.2.3 HookCodeFactory 類
HookCodeFactory 的內(nèi)容相對(duì)較多,不過(guò)沒(méi)關(guān)系,我們暫時(shí)只看當(dāng)前 hook.call 執(zhí)行流程相關(guān)的代碼段即可:
/****?@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);??//?注冊(cè)的事件回調(diào)數(shù)組}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?內(nèi)部獲取?options?和用戶入?yún)his.options?=?options;this._args?=?options.args.slice();}deinit()?{??//?移除?init?的處理this.options?=?undefined;this._args?=?undefined;}args()?{??//?返回參數(shù)字符串let?allArgs?=?this._args;if?(allArgs.length?===?0)?{return?"";}?else?{return?allArgs.join(",?");}} }可以看到 setup 方法會(huì)將當(dāng)前已注冊(cè)事件的回調(diào)統(tǒng)一放到數(shù)組 this._x 中,后續(xù)要觸發(fā)所有訂閱事件回調(diào),只需要按順序執(zhí)行 this._x 即可。
而 create 則通過(guò) new Function(args, functionString) 構(gòu)造了一個(gè)函數(shù),該函數(shù)最終由被重寫(xiě)的 call 觸發(fā)。
所以這里我們只需要再確認(rèn)下 this.content 方法執(zhí)行后的返回值,就能知道最終 call 方法所執(zhí)行的函數(shù)是什么。
回看前面的代碼,content 是在 SyncHook.js 中定義的:
/****?@file?SyncHook.js?****/class?SyncHookCodeFactory?extends?HookCodeFactory?{content({?onDone?})?{return?this.callTapsSeries({??//?實(shí)際上是?this.callTapsSeries?的調(diào)用onDone});} }順藤摸瓜,我們回 HookCodeFactory.js 接著看 this.callTapsSeries 的實(shí)現(xiàn):
/****?@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()?會(huì)返回上一次存儲(chǔ)的?codecode?+=?onDone();}break;}return?code;}callTap 方法每次執(zhí)行會(huì)生成和返回單個(gè)訂閱事件執(zhí)行代碼字符串,例如:
var?_fn0?=?_x[0]; _fn0(contry,?city,?people);callTapsSeries 會(huì)遍歷訂閱數(shù)組并逐次調(diào)用 callTap,最后將全部訂閱事件的執(zhí)行代碼字符串拼接起來(lái)。
理解 callTapsSeries 方法的關(guān)鍵點(diǎn),是理解 current 變量在每次迭代前后的變化。
假設(shè)存在 4 個(gè)訂閱事件,則 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 參數(shù)是為了在遍歷開(kāi)始時(shí),作為 current 的默認(rèn)值使用的。
示例:
每次用戶調(diào)用 syncHook.call 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: var?_fn0?=?_x[0]; _fn0(contry,?city,?people); var?_fn1?=?_x[1]; _fn1(contry,?city,?people);最終在 create 方法中通過(guò) new Function 創(chuàng)建為常規(guī)函數(shù)供 call 調(diào)用:
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); }執(zhí)行后, this._x 里的事件回調(diào)會(huì)按順序逐個(gè)執(zhí)行。
三、SyncBailHook 的基礎(chǔ)實(shí)現(xiàn)
3.1 介紹
SyncBailHook 也是一個(gè)同步鉤子,不同于 SyncHook 的地方是,如果某個(gè)訂閱事件的回調(diào)函數(shù)返回了非 undefined 的值,那么會(huì)中斷該鉤子后續(xù)其它訂閱回調(diào)的調(diào)用:
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;??//?設(shè)置了非?undefined?的返回值 })//?因?yàn)?event-2?設(shè)置了返回值,所以后續(xù)的?event-3、event-4?都不會(huì)執(zhí)行 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) })//?執(zhí)行訂閱回調(diào) hook.call('USA',?'NYC',?'Trump')/******?下方為輸出?******/ event-1:?USA?NYC?Trump event-2:?USA?NYC?Trump在上方示例中,因?yàn)?event-2 的回調(diào)返回了 null,故中斷了后續(xù)其它訂閱回調(diào)的執(zhí)行。
3.2 代碼實(shí)現(xiàn)
SyncBailHook 的入口模塊為 SyncBailHook.js,它相對(duì)于前一節(jié)的 SyncHook.js 而言,只是多了一個(gè) 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 都是模板參數(shù),它們執(zhí)行后都會(huì)返回模板字符串,用于在 callTap 方法里拼接函數(shù)代碼段。
我們需要在調(diào)用 this.content 和 this.callTapsSeries 的地方分別做點(diǎn)修改,讓它們利用這個(gè)新增的模板參數(shù),來(lái)實(shí)現(xiàn) SyncBailHook 的功能。
⑴ content 調(diào)用處的改動(dòng)
/****?@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;}這里的實(shí)現(xiàn),其實(shí)等同于 SyncBailHookCodeFactory 調(diào)用 content 時(shí)不傳 onResult 的簡(jiǎn)易處理:
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 調(diào)用處的改動(dòng)
在 2.2.3 小節(jié)末尾,我們知道 this.callTapsSeries 中最關(guān)鍵的實(shí)現(xiàn),是利用了 current 的變化和傳遞,來(lái)實(shí)現(xiàn)各訂閱事件回調(diào)執(zhí)行代碼字符串的拼接。
對(duì)于 SyncBailHook 的需求,我們可以利用 onResult 把 current() 的模板包起來(lái)(把 onResult 的第三個(gè)參數(shù)設(shè)為 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?則設(shè)為?false//?新增?onResult?傳參,把?current?包起來(lái)onResult:onResult?&&(result?=>?{return?onResult(j,?result,?current);}),});current?=?()?=>?content;}code?+=?current();return?code;}callTap(tapIndex,?{?onDone,?onResult?})?{??//?新增?onResult?參數(shù)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}`);}//?對(duì)?SyncBailHook?來(lái)說(shuō)?onDone=falseif?(onDone)?{code?+=?onDone();}break;}return?code;}這樣每次執(zhí)行 callTap 時(shí),我們都能獲得如下模板:
//?假設(shè)?I?為遍歷索引 var?_fnI?=?_x[I]; var?_resultI?=?_fnI(...args); if(_resultI?!==?undefined)?{return?_resultI; }?else?{[current()?返回的模板,即前一次迭代生成的代碼段] }示例
每次用戶調(diào)用 syncBailHook.call 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: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 依舊為同步鉤子,不過(guò)它會(huì)把前一個(gè)訂閱回調(diào)所返回的內(nèi)容,作為第一個(gè)參數(shù)傳遞給后續(xù)的訂閱回調(diào):
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';??//?設(shè)置了返回值 })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 代碼實(shí)現(xiàn)
通過(guò)前面兩節(jié),我們知道了讓訂閱事件回調(diào)按鉤子邏輯來(lái)執(zhí)行的原理,不外乎是通過(guò)傳入 onXXXX 的模板參數(shù),來(lái)生成 hook.call 最終調(diào)用的函數(shù)代碼。
SyncWaterfallHook 的實(shí)現(xiàn)也非常簡(jiǎn)單,只需要調(diào)整 onDone 和 onResult 兩個(gè)模板參數(shù)即可:
/****?@file?SyncWaterfallHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?SyncWaterfallHookCodeFactory?extends?HookCodeFactory?{content({?onResult?})?{return?this.callTapsSeries({onResult:?(i,?result,?next)?=>?{??//?修改點(diǎn)let?code?=?"";code?+=?`if(${result}?!==?undefined)?{\n`;code?+=?`${this._args[0]}?=?${result};\n`;code?+=?`}\n`;code?+=?next();return?code;},onDone:?()?=>?onResult(this._args[0]),??//?修改點(diǎn)});} }//?...略function?SyncWaterfallHook(args?=?[],?name?=?undefined)?{//?...略 }module.exports?=?SyncWaterfallHook;onDone 為訂閱對(duì)象數(shù)組遍歷時(shí)的初始化模板函數(shù),執(zhí)行后會(huì)生成 return ${this._args[0]};\n 字符串。
onResult 為訂閱對(duì)象數(shù)組遍歷時(shí)的非初始化模板函數(shù),會(huì)判斷上一個(gè)訂閱回調(diào)返回值是否非 undefined,是則將 syncWaterfallHook.call 的第一個(gè)參數(shù)改為此返回值,再拼接上一次遍歷生成的模板內(nèi)容。
示例
每次用戶調(diào)用 syncWaterfallHook.call 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: 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 介紹
這是最后一個(gè)同步鉤子了,SyncLoopHook 表示如果存在某個(gè)訂閱事件回調(diào)返回了非 undefined 的值,則全部訂閱事件回調(diào)從頭執(zhí)行:
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 代碼實(shí)現(xiàn)
SyncLoopHook “從頭執(zhí)行全部回調(diào)”的邏輯比較特殊,舊的方法已經(jīng)無(wú)法滿足該需求,所以 Tapable 為其新開(kāi)了一個(gè) callTapsLooping 方法來(lái)處理:
/****?@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 方法的實(shí)現(xiàn):
/****?@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 在模板的外層包了個(gè) do while 循環(huán):
var?_loop; do?{_loop?=?false;${?callTapsSeries?生成的模板?} }?while(_loop)這里的后續(xù)邏輯很好猜測(cè):callTapsSeries 生成的模板,只需要判斷訂閱回調(diào)返回值是否為 undefined,然后修改 _loop 即可。
而 callTapsLooping 傳入 callTapsSeries 的 onResult 參數(shù)完善了此塊邏輯:
示例
每次用戶調(diào)用 syncLoopHook.call 時(shí),callTapsLooping 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: 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 介紹
我們已經(jīng)介紹完了 Tapable 的同步鉤子,接下來(lái)逐個(gè)介紹 Tapable 中異步相關(guān)的幾個(gè)鉤子,首先介紹最簡(jiǎn)單的 AsyncSeriesHook。
AsyncSeriesHook 表示一個(gè)異步串行的鉤子,可以通過(guò) hook.tapAsync 或 hook.tapPromise 方法,來(lái)注冊(cè)異步的事件回調(diào)。
這些訂閱事件的回調(diào)依舊是逐個(gè)執(zhí)行,即必須等到上一個(gè)異步回調(diào)通知鉤子它已經(jīng)執(zhí)行完畢了,才能開(kāi)始下一個(gè)異步回調(diào):
//?初始化異步串行鉤子 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);}); })//?執(zhí)行訂閱回調(diào) 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!對(duì)于使用 hook.tapAsync 來(lái)訂閱事件的異步回調(diào),可以通過(guò)執(zhí)行最后一個(gè)參數(shù)來(lái)通知鉤子“我已經(jīng)執(zhí)行完畢,可以接著執(zhí)行后面的回調(diào)了”;
對(duì)于使用 hook.tapPromise 來(lái)訂閱事件的異步回調(diào),需要返回一個(gè) Promise,當(dāng)其狀態(tài)為 resolve 時(shí),鉤子才會(huì)開(kāi)始執(zhí)行后續(xù)其它訂閱回調(diào)。
另外需要留意下,AsyncSeriesHook 鉤子使用新的 hook.callAsync 來(lái)執(zhí)行訂閱回調(diào)(而不再是 hook.call),且支持傳入回調(diào)(最后一個(gè)參數(shù)),在全部訂閱事件執(zhí)行完畢后觸發(fā)。
6.2 代碼實(shí)現(xiàn)
首先是 AsyncSeriesHook 模塊的代碼,結(jié)構(gòu)和 SyncHook 是基本一樣的:
/****?@file?AsyncSeriesHook.js?****/ const?Hook?=?require("./Hook"); const?HookCodeFactory?=?require("./HookCodeFactory");class?AsyncSeriesHookCodeFactory?extends?HookCodeFactory?{content({?onDone,?onError?})?{??//?新增?onErrorreturn?this.callTapsSeries({//?新增?onError,處理異步回調(diào)中的錯(cuò)誤onError:?(i,?err,?next,?doneBreak)?=>?onError(err)?+?doneBreak(true),onDone});} }//?略...function?AsyncSeriesHook(args?=?[],?name?=?undefined)?{//?略... }module.exports?=?AsyncSeriesHook;這里我們新增了 onError 方法來(lái)處理異步回調(diào)中的錯(cuò)誤。
AsyncSeriesHook 鉤子實(shí)現(xiàn)的關(guān)鍵點(diǎn),是對(duì)其幾個(gè)專用方法 hook.tapAsync、hook.tapPromise 和 hook.callAsync 的實(shí)現(xiàn),我們先到 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;可以看到這幾個(gè)新增的方法所調(diào)用的接口跟之前的 hoo.tap、hook.call 一致,只是把訂閱對(duì)象信息的 type 標(biāo)記為 async/promise 罷了。
我們繼續(xù)到 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?參數(shù)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 執(zhí)行時(shí),先調(diào)用的是 create 方法里 case "async" 的代碼塊。
從傳入 this.content 的參數(shù)可以猜測(cè)到,hook.callAsync 的函數(shù)模板里,會(huì)使用 Node Error First 異步回調(diào)的格式來(lái)書(shū)寫(xiě)相應(yīng)邏輯:
function?callback(err,?nextAsyncFunc)?{if?(err)?{//?錯(cuò)誤處理}?else?{nextAsyncFunc?&&?nextAsyncFunc(callback)} };另外留意 this.args 方法的改動(dòng) —— 在返回用戶入?yún)⒆址耐瑫r(shí),可以通過(guò)傳入 before/after,往返回的字符串前后再多插一個(gè)自定義參數(shù)。這也是為何 hook.callAsync 相較同步鉤子的 hook.call,可以多傳入一個(gè)可執(zhí)行的回調(diào)參數(shù)的原因。
我們接著看 callTap 方法里新增的對(duì) tapAsync 和 tapPromise 訂閱回調(diào)的模板處理邏輯。
⑴ 生成 tapAsync 訂閱回調(diào)模板
/****?@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?類型處理(通過(guò)?hook.tapAsync?訂閱的回調(diào)模板處理)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;}} }該代碼段會(huì)生成如下模板:
//?假設(shè)遍歷索引?tapIndex?為?I var?_fnI?=?_x[I]; _fnI(passenger,?function(_errI)?{if(_errI)?{_callback(_errI);}?else?{${?前一次遍歷的模板?}} });即生成了一個(gè) Error First 的異步回調(diào)嵌套模板。
留意模板中的 _callback 是最終在 create 方法中,通過(guò) new Function 時(shí)傳入的形參,代表用戶傳入 hook.callAsync 的回調(diào)參數(shù)(最后一個(gè)參數(shù),在報(bào)錯(cuò)或全部訂閱事件結(jié)束時(shí)候觸發(fā)):
fn?=?new?Function(this.args({after:?"_callback"}),this.header()?+?this.content(...) );示例
用戶調(diào)用 asyncSeriesHook.call 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: 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 訂閱回調(diào)模板
分析完 hook.tapAsync 方式訂閱的回調(diào)的模板生成方式,我們來(lái)看下 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?類型處理(通過(guò)?hook.tapPromise?訂閱的回調(diào)模板處理)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;}} }該代碼段會(huì)生成如下模板:
//?假設(shè)遍歷索引?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 的能力來(lái)決定下一個(gè)訂閱回調(diào)的執(zhí)行時(shí)機(jī):
示例
用戶調(diào)用 asyncSeriesHook.callAsync 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 const?hook?=?new?AsyncSeriesHook(['passenger']);hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{//?略... })hook.tapPromise('Back?to?Shenzhen',?(passenger)?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// callTapsSeries 生成的函數(shù)片段字符串: 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 的表現(xiàn)基本一致,不過(guò)會(huì)判斷訂閱事件回調(diào)的返回值是否為 undefined,如果非 undefined 會(huì)中斷后續(xù)訂閱回調(diào)的執(zhí)行:
const?hook1?=?new?AsyncSeriesBailHook(['passenger']);hook1.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);setTimeout(()?=>?{callback(true);??//?設(shè)置了返回值},?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);??//?設(shè)置了返回值},?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 代碼實(shí)現(xiàn)
回顧第三節(jié) SyncBailHook 的實(shí)現(xiàn)我們可以得知,它相較 SyncHook 而言只是新增了一個(gè) onResult 來(lái)進(jìn)一步處理模板邏輯。
AsyncSeriesBailHook 的實(shí)現(xiàn)也是如此,只需要在 AsyncSeriesHook 的基礎(chǔ)上添加一個(gè) onResult,對(duì)上一個(gè)訂閱回調(diào)返回值進(jìn)行判斷即可:
/****?@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 傳進(jìn)來(lái)后的值為://?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;}我們?cè)谙路降氖纠?#xff0c;看看模板發(fā)生了哪些改動(dòng)。
示例
用戶調(diào)用 asyncSeriesBailHook.callAsync 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
⑴ hook.tapAsync 訂閱回調(diào)對(duì)應(yīng)模板:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: 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 訂閱回調(diào)對(duì)應(yīng)模板:
//?外部調(diào)用 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);??//?設(shè)置了返回值},?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 生成的函數(shù)片段字符串: 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); });具體變更點(diǎn)見(jiàn)代碼中的注釋。
Tapable 中的模板拼接乍一看挺復(fù)雜,但它的實(shí)現(xiàn),肯定是先思考最終成型的模板應(yīng)該長(zhǎng)怎樣,再根據(jù)需求在 callTap 方法中添加對(duì)應(yīng)邏輯。因此,通過(guò)最終的模板來(lái)反推功能的實(shí)現(xiàn),也是一種理解 Tapable 源碼的方式。
八、AsyncSeriesWaterfallHook
8.1 介紹
AsyncSeriesWaterfallHook 也是異步串行的鉤子,不過(guò)在執(zhí)行時(shí),上一個(gè)訂閱回調(diào)的返回值會(huì)傳遞給下一個(gè)訂閱回調(diào),并覆蓋掉新訂閱回調(diào)的第一個(gè)參數(shù):
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?的寫(xiě)法 })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 代碼實(shí)現(xiàn)
和 4.2 小節(jié) SyncWaterfallHook 的實(shí)現(xiàn)一樣,AsyncSeriesWaterfallHook 可以通過(guò)修改 onResult 和 onDone 方式來(lái)實(shí)現(xiàn):
/****?@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;示例
用戶調(diào)用 asyncSeriesWaterfallHook.callAsync 時(shí),callTapsSeries 生成的函數(shù)片段字符串:
//?外部調(diào)用 hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook.tapPromise('Fly?to?Tokyo',?(time)?=>?{//?略... })hook.tapAsync('Fly?to?Shanghai',?(time,?callback)?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// callTapsSeries 生成的函數(shù)片段字符串: 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 是一個(gè)異步并行的鉤子,全部訂閱回調(diào)都會(huì)同時(shí)并行觸發(fā):
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 代碼實(shí)現(xiàn)
如同 SyncsLoopHook 鉤子需要新增 this.callTapsLooping 方法,在 this.callTapsSeries 外頭多套一層模板來(lái)實(shí)現(xiàn)具體需求。
這次的 AsyncParallelHook 鉤子也需要新增一個(gè) this.callTapsParallel 方法實(shí)現(xiàn)并行能力,但會(huì)摒棄串行的 this.callTapsSeries 接口,改而直接調(diào)用 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 的具體實(shí)現(xiàn):
/****?@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 新增的模板會(huì)遍歷訂閱對(duì)象,然后逐個(gè)扔給 callTap 生成單個(gè)訂閱回調(diào)的模板,再將它們拼接起來(lái)同步執(zhí)行:
do?{??//?形成閉包,避免?const/let?變量提升到外部_fn0(...);_fn1(...);..._fnN(...); }?while(false)另外新增了計(jì)數(shù)器變量 _counter,初始化值為訂閱對(duì)象數(shù)量,每次執(zhí)行完單個(gè)訂閱回調(diào)會(huì)自減一,訂閱回調(diào)可以通過(guò)它判斷自己是否最后一個(gè)回調(diào)(如果是則執(zhí)行用戶傳入 hook.callAsync 的“事件終止”回調(diào))。
示例
用戶調(diào)用 asyncSeriesHook.callAsync 時(shí),callTapsParallel 生成的函數(shù)片段字符串:
//?外部調(diào)用 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 生成的函數(shù)片段字符串: 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 基本一致,但如果前一個(gè)訂閱回調(diào)返回了非 undefined 的值,會(huì)中斷后續(xù)其它訂閱回調(diào)的執(zhí)行,并觸發(fā)用戶傳入 hook.callAsync 的“事件終止”回調(diào):
hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{console.log(`${passenger}?is?on?the?way?to?Beijing...`);//?注意這里不走異步處理,直接調(diào)用?callbackcallback(null,?true) })hook.tapPromise('Fly?to?Tokyo',?(passenger)?=>?{//?執(zhí)行前發(fā)現(xiàn)上個(gè)訂閱回調(diào)返回了?true,故不會(huì)執(zhí)行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!如果一個(gè)異步的訂閱回調(diào)會(huì)返回非 undefined 的值,但在它返回前,其它并行執(zhí)行的訂閱回調(diào)會(huì)照常執(zhí)行不受影響。這種情況唯一受影響的,是“事件終止”回調(diào)的執(zhí)行位置:
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!??//?“事件終止”回調(diào)打印的內(nèi)容 [Shanghai]?Arrived [Tokyo]?Arrived可以看到“事件終止”回調(diào)會(huì)在 Fly to Beijing 訂閱回調(diào)結(jié)束后觸發(fā),因?yàn)樵撚嗛喕卣{(diào)返回了 true。另外因?yàn)樵摶卣{(diào)是異步的,所以其它的訂閱回調(diào)會(huì)照常被并發(fā)執(zhí)行。
10.2 代碼實(shí)現(xiàn)
AsyncParallelBailHook 的實(shí)現(xiàn)比較粗暴直接,是在 AsyncParallelBailHook.js 里定義 content 的方法中,在模板前面新增一段內(nèi)容:
/****?@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 參數(shù),它可傳遞給 this.callTapsParallel 來(lái)靈活處理 callTap 方法生成的模板:
/****?@file?HookCodeFactory.js?****/ callTapsParallel({onError,onResult,onDone,onTap?=?(i,?run)?=>?run()??//?新增 })?{//?略...for?(let?i?=?0;?i?<?this.options.taps.length;?i++)?{//?略...//?新增改動(dòng),調(diào)用?this.callTap?的地方使用?onTap?包起來(lái)code?+=?onTap(i,()?=>this.callTap(i,?{//?略...}),done,doneBreak);}//?略...return?code; }content 方法為模板新增了一個(gè) _results 數(shù)組用于存儲(chǔ)訂閱回調(diào)的執(zhí)行信息(返回值和錯(cuò)誤);還新增一個(gè) _checkDone 方法,通過(guò)遍歷 _results 來(lái)檢查事件是否應(yīng)該結(jié)束 —— 若發(fā)現(xiàn)某個(gè)訂閱回調(diào)執(zhí)行出錯(cuò),或者返回了非 undefined 值,_checkDone 方法會(huì)返回 true 并執(zhí)行用戶傳入的“事件終止”回調(diào))。
每個(gè)訂閱回調(diào)執(zhí)行后,會(huì)把其執(zhí)行信息寫(xiě)入 _results 數(shù)組并執(zhí)行 _checkDone()。
示例
用戶調(diào)用 asyncParallelBailHook.callAsync 時(shí),content 方法生成的函數(shù)片段字符串:
//?外部調(diào)用 hook.tapAsync('Fly?to?Beijing',?(passenger,?callback)?=>?{//?略... })hook.tapPromise('Fly?to?Tokyo',?()?=>?{//?略... })hook.callAsync('VJ',?()?=>?{});// content 方法生成的函數(shù)片段字符串: 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 不對(duì)外暴露的隱藏鉤子,但它并不神秘 —— 它和第 5 節(jié)所介紹的 SyncLoopHook 的表現(xiàn)一致,訂閱回調(diào)都是按順序串行執(zhí)行的(前一個(gè)訂閱回調(diào)執(zhí)行完了才會(huì)開(kāi)始執(zhí)行下一個(gè)回調(diào)),若有回調(diào)返回了非 undefined 的值,會(huì)中斷進(jìn)度從頭開(kāi)始整個(gè)流程。區(qū)別只是在 AsyncSeriesLoopHook 里被執(zhí)行的訂閱回調(diào)是異步的:
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 代碼實(shí)現(xiàn)
AsyncSeriesLoopHook 模塊和 SyncLoopHook 模塊基本是一樣的,都使用了 this.callTapsLooping 接口來(lái)實(shí)現(xiàn)串行執(zhí)行、循環(huán)執(zhí)行的能力:
/****?@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 接口只能處理同步的訂閱回調(diào),為了讓其可以處理異步的訂閱回調(diào),需要加一點(diǎn)改動(dòng):
/****?@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; }這里的改動(dòng)相當(dāng)于在最外層包了一個(gè) _looper 函數(shù)方便在異步的訂閱回調(diào)返回了非 undefined 的時(shí)候,來(lái)遞歸調(diào)用自己實(shí)現(xiàn)循環(huán)。
SyncLoopHook 的那套 do-while 只適合同步的訂閱回調(diào),因?yàn)槿绻錾袭惒降挠嗛喕卣{(diào),等它執(zhí)行完畢時(shí) do-while 已經(jīng)執(zhí)行結(jié)束了,無(wú)法再循環(huán)。
示例
用戶調(diào)用 asyncSeriesLoopHook.callAsync 時(shí),callTapsLooping 生成的函數(shù)片段字符串:
//?外部調(diào)用? 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 生成的函數(shù)片段字符串: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;??//?沒(méi)有意義,因?yàn)榛卣{(diào)是異步的,while?已經(jīng)結(jié)束了if?(_loopAsync)?_looper();??//?需要調(diào)用?_looper?來(lái)重新執(zhí)行}?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 的全部鉤子的基礎(chǔ)實(shí)現(xiàn),我們可以開(kāi)始考慮提升一下鉤子的更多能力,首先讓鉤子們支持?jǐn)r截的功能。
Tappable 中的所有鉤子都支持設(shè)置攔截器,可以在鉤子執(zhí)行的各階段進(jìn)行攔截。主要的攔截接口有如下幾個(gè):
register:訂閱前觸發(fā)攔截,調(diào)用 hook.intercept 方法時(shí)執(zhí)行攔截回調(diào)。當(dāng)前鉤子有多少個(gè)訂閱事件就會(huì)執(zhí)行多少次 register 攔截回調(diào),可以在該攔截回調(diào)里修改訂閱者信息。
call:用戶調(diào)用 hook.call/callAsync 時(shí)觸發(fā),在訂閱事件的回調(diào)執(zhí)行前執(zhí)行,參數(shù)為用戶傳參。只會(huì)觸發(fā)一次。
loop:loop 類型鉤子每次循環(huán)起始時(shí)觸發(fā)(排在 call 攔截器后面),參數(shù)為用戶傳參。循環(huán)幾次就會(huì)觸發(fā)幾次。
tap:調(diào)用 hook.call/callAsync 時(shí)觸發(fā),在訂閱事件的回調(diào)執(zhí)行前執(zhí)行(排在 call 和 loop 攔截器后面),參數(shù)為訂閱者信息。有多個(gè)訂閱回調(diào)就會(huì)執(zhí)行多次。
error:調(diào)用 hook.call/callAsync 時(shí)觸發(fā),攔截時(shí)機(jī)為執(zhí)行訂閱回調(diào)出錯(cuò)時(shí),參數(shù)為錯(cuò)誤對(duì)象。
done:調(diào)用 hook.call/callAsync 時(shí)觸發(fā),攔截時(shí)機(jī)為全部訂閱回調(diào)執(zhí)行完畢的時(shí)候(排在用戶傳入的“事件終止”回調(diào)前面),沒(méi)有參數(shù)。
攔截器示例 - 同步訂閱回調(diào):
const?{?SyncHook?}?=?require('tapable');//?初始化同步鉤子 const?hook?=?new?SyncHook(["contry",?"city",?"people"]);//?設(shè)置攔截器 hook.intercept({//?訂閱前觸發(fā)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;??//?訂閱者的信息會(huì)變成修改后的},//?call?方法調(diào)用時(shí)觸發(fā)call:?(...args)?=>?{console.log('[call-intercept]',?args);},//?調(diào)用訂閱事件回調(diào)前觸發(fā)tap:?(options)?=>?{console.log('[tap-intercept]',?options);}, });//?注冊(cè)事件 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) })//?執(zhí)行事件 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.攔截器示例 - 異步訂閱回調(diào):
const?hook?=?new?AsyncSeriesLoopHook(['name',?'country']);hook.intercept({//?訂閱前觸發(fā)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;??//?訂閱者的信息會(huì)變成修改后的},//?call?方法調(diào)用時(shí)觸發(fā)call(...args)?{console.log('[call-intercept]',?args);},//?調(diào)用訂閱事件回調(diào)前觸發(fā)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!攔截器還支持多個(gè)配置,會(huì)依次執(zhí)行:
const?hook?=?new?AsyncSeriesLoopHook(['name',?'country']);//?配置第一個(gè)攔截器 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.')} });//?配置第二個(gè)攔截器 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!攔截器是個(gè)很有意思的功能,是各工具“生命周期”的底層鉤子,我們來(lái)看下 Tapable 中是如何實(shí)現(xiàn)攔截器的。
12.2 代碼實(shí)現(xiàn)
12.2.1 intercept 入口和 register 攔截器
首先要實(shí)現(xiàn)的自然是 hook.intercept 的接口,我們需要回到 Hook.js 中添加該方法,并新增一個(gè)數(shù)組來(lái)存放攔截器配置:
/****?@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++)?{//?執(zhí)行?register?攔截器,用返回值替換訂閱對(duì)象信息this.taps[i]?=?interceptor.register(this.taps[i]);}}} }在用戶注冊(cè)攔截器的時(shí)候(調(diào)用 hook.intercept),會(huì)將攔截器配置對(duì)象存入數(shù)組 this.interceptors,然后遍歷訂閱事件對(duì)象,逐個(gè)觸發(fā) register 攔截器,并用攔截回調(diào)的返回值來(lái)替換訂閱對(duì)象信息。這也是為何我們可以在 register 攔截階段直接修改訂閱對(duì)象信息。
12.2.2 call、error、done 攔截器
我們都知道 Tapable 是通過(guò)模板拼接來(lái)完成其全部能力的,攔截器的實(shí)現(xiàn)方式也不例外。
試想一下,我們可以通過(guò)存儲(chǔ)于 this.interceptors 的數(shù)組里獲取到攔截器配置,自然也可以在需要攔截的地方,將 this.interceptors[n].interceptorName() 字符串嵌入模板對(duì)應(yīng)位置,最終執(zhí)行模板函數(shù)時(shí),就會(huì)在適當(dāng)?shù)臅r(shí)間點(diǎn)執(zhí)行對(duì)應(yīng)的攔截回調(diào)。
例如在 HookCodeFactory.js 中,我們可以新增一個(gè) contentWithInterceptors 方法,在調(diào)用 this.content 前觸發(fā) ?call 攔截器,并修改傳入 this.content 的 onError 和 onDone 模板,讓它們?cè)趫?zhí)行時(shí)分別先觸發(fā) 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 方法中調(diào)用 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 開(kāi)始執(zhí)行時(shí)觸發(fā)的,它的實(shí)現(xiàn)很簡(jiǎn)單:
/****?@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; }它會(huì)生成這樣的模板內(nèi)容:
//?假設(shè)遍歷索引為?I,且有兩個(gè)攔截器配置對(duì)象 var?_tapI?=?tapOptionsI; _interceptors[0].tap(_tapI) _interceptors[1].tap(_tapI)12.2.4 loop 攔截器
loop 攔截器只需要在 callTapsLooping 的 do-while 模板開(kāi)頭插入攔截代碼即可:
/****?@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 中的幾個(gè)攔截器就這么被實(shí)現(xiàn)了,沒(méi)想象中的復(fù)雜對(duì)吧?
十三、HookMap
13.1 介紹
HookMap 是 Tapable 的一個(gè)輔助類(helper),利用它可以更好地封裝我們的各種鉤子:
const?keyedHook?=?new?HookMap(key?=>?new?SyncHook(["desc"]));//?創(chuàng)建名為“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)?});//?創(chuàng)建名為“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 代碼實(shí)現(xiàn)
HookMap 使用了 this._factory 來(lái)存儲(chǔ)用戶在初始化時(shí)傳入的鉤子構(gòu)造函數(shù)(鉤子工廠),后續(xù)用戶調(diào)用 hookMap.for 時(shí)會(huì)通過(guò)該構(gòu)造函數(shù)生成指定類型的鉤子,并以鉤子名稱為 key 存入一個(gè) Map 對(duì)象,后續(xù)如果需要獲取該鉤子,從 Map 對(duì)象查找它的名稱即可:
/****?@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;??//?支持鏈?zhǔn)秸{(diào)用}let?newHook?=?this._factory(key);this._map.set(key,?newHook);return?newHook;??//?支持鏈?zhǔn)秸{(diào)用} }module.exports?=?HookMap;留意 for 的開(kāi)頭會(huì)先判斷是否已經(jīng)構(gòu)建了該名稱的鉤子,如果是則直接返回。
我們就這樣完成了 HookMap 的基礎(chǔ)能力,可見(jiàn)它就是一個(gè)語(yǔ)法糖,實(shí)現(xiàn)相對(duì)簡(jiǎn)單。
另外 HookMap 支持一個(gè)名為 factory 的攔截器,它可以修改 HookMap 的鉤子構(gòu)造函數(shù)(this._factory),對(duì)新建的鉤子會(huì)生效:
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?的鉤子,攔截器不會(huì)影響,它依舊是?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 ******/它的實(shí)現(xiàn)也很簡(jiǎn)單,這里不再贅述:
/****?@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;??//?如果已有同名鉤子,攔截器不會(huì)生效}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
這是最后一個(gè)要介紹的 Tapable 的模塊了,它也是一個(gè)語(yǔ)法糖,方便你批量操作多個(gè)鉤子:
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 ******/其實(shí)現(xiàn)非常簡(jiǎn)單,只是一個(gè)普通的封裝模塊,將傳入的鉤子們存在 this.hooks 中,在調(diào)用內(nèi)部方法的時(shí)候通過(guò) for of 來(lái)遍歷鉤子和執(zhí)行對(duì)應(yīng)接口:
/****?@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;十五、小結(jié)
以上就是全部關(guān)于 Tapable 的分析了,從中我們了解到了 Tapable 的實(shí)現(xiàn)是基于模板的拼接,這是個(gè)很有創(chuàng)意的形式,有點(diǎn)像搭積木,把各鉤子的訂閱回調(diào)按相關(guān)邏輯一層層搭建成型,這其實(shí)不是很輕松的事情。
在掌握了 Tapable 各種鉤子、攔截器的執(zhí)行流程和實(shí)現(xiàn)之后,也相信你會(huì)對(duì) Webpack 的工作流程有了更進(jìn)一步的了解,畢竟 Webpack 的工作流程不外乎就是將各個(gè)插件串聯(lián)起來(lái),而 Tapable 幫忙實(shí)現(xiàn)了這一事件流機(jī)制。
另外這么長(zhǎng)的文章應(yīng)該存在一些錯(cuò)別字或語(yǔ)病,歡迎大家評(píng)論指出,我再一一修改。
最后感謝大家能耐心讀完本文,希望你們能有所收獲,共勉~
總結(jié)
以上是生活随笔為你收集整理的【Webpack】1256- 硬核解析 Webpack 事件流核心!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ES6 模块化【暴露、引入、引入并暴露】
- 下一篇: 神经网络分类四种模型,神经网络分类特点区