谈谈Tapable的前世今生

开发 前端
tapable 是一个类似于 Node.js 中的 EventEmitter 的库,但更专注于自定义事件的触发和处理。webpack 通过 tapable 将实现与流程解耦,所有具体实现通过插件的形式存在。

[[406057]]

tapable 是一个类似于 Node.js 中的 EventEmitter 的库,但更专注于自定义事件的触发和处理。webpack 通过 tapable 将实现与流程解耦,所有具体实现通过插件的形式存在。

Tapable 和 webpack 的关系

webpack 是什么?

本质上,webpack 是一个用于现代 JavaScript 应用程序的 静态模块打包工具。当 webpack 处理应用程序时,它会在内部构建一个 依赖图(dependency graph),此依赖图对应映射到项目所需的每个模块,并生成一个或多个 bundle。

webpack 的重要模块

  • 入口(entry)
  • 输出(output)
  • loader(对模块的源代码进行转换)
  • plugin(webpack 构建流程中的特定时机注入扩展逻辑来改变构建结果或做你想要的事)

插件(plugin)是 webpack 的支柱功能。webpack 自身也是构建于你在 webpack 配置中用到的相同的插件系统之上。

webpack 的构建流程

webpack 本质上是一种事件流的机制,它的工作流程就是将各个插件串联起来,而实现这一切的核心就是 Tapable。webpack 中最核心的负责编译的 Compiler 和负责创建 bundle 的 Compilation 都是 Tapable 的实例(webpack5 前)。webpack5 之后是通过定义属性名为 hooks 来调度触发时机。Tapable 充当的就是一个复杂的发布订阅者模式

以 Compiler 为例:

  1. // webpack5 前,通过继承 
  2. ... 
  3. const { 
  4.  Tapable, 
  5.  SyncHook, 
  6.  SyncBailHook, 
  7.  AsyncParallelHook, 
  8.  AsyncSeriesHook 
  9. } = require("tapable"); 
  10. ... 
  11. class Compiler extends Tapable { 
  12.  constructor(context) { 
  13.   super(); 
  14.   ... 
  15.  } 
  16.  
  17. // webpack5 
  18. ... 
  19. const { 
  20.  SyncHook, 
  21.  SyncBailHook, 
  22.  AsyncParallelHook, 
  23.  AsyncSeriesHook 
  24. } = require("tapable"); 
  25. ... 
  26. class Compiler { 
  27.  constructor(context) { 
  28.   this.hooks = Object.freeze({ 
  29.    /** @type {SyncHook<[]>} */ 
  30.    initialize: new SyncHook([]), 
  31.  
  32.    /** @type {SyncBailHook<[Compilation], boolean>} */ 
  33.    shouldEmit: new SyncBailHook(["compilation"]), 
  34.    ... 
  35.   }) 
  36.  } 
  37.  ... 

Tapable 的使用姿势

tapable 对外暴露了 9 种 Hooks 类。这些 Hooks 类的作用就是通过实例化来创建一个执行流程,并提供注册和执行方法,Hook 类的不同会导致执行流程的不同。

  1. const { 
  2.  SyncHook, 
  3.  SyncBailHook, 
  4.  SyncWaterfallHook, 
  5.  SyncLoopHook, 
  6.  AsyncParallelHook, 
  7.  AsyncParallelBailHook, 
  8.  AsyncSeriesHook, 
  9.  AsyncSeriesBailHook, 
  10.  AsyncSeriesWaterfallHook 
  11.  } = require("tapable"); 

每个 hook 都能被注册多次,如何被触发取决于 hook 的类型

按同步、异步(串行、并行)分类

  • Sync:只能被同步函数注册,如 myHook.tap()
  • AsyncSeries:可以被同步的,基于回调的,基于 promise 的函数注册,如 myHook.tap(),myHook.tapAsync() , myHook.tapPromise()。执行顺序为串行
  • AsyncParallel:可以被同步的,基于回调的,基于 promise 的函数注册,如 myHook.tap(),myHook.tapAsync() , myHook.tapPromise()。执行顺序为并行

按执行模式分类

  • Basic:执行每一个事件函数,不关心函数的返回值

  • Bail:执行每一个事件函数,遇到第一个结果 result !== undefined 则返回,不再继续执行

  • Waterfall:如果前一个事件函数的结果 result !== undefined,则 result 会作为后一个事件函数的第一个参数

  • Loop:不停的循环执行事件函数,直到所有函数结果 result === undefined

使用方式

Hook 类

使用简单来说就是下面步骤

  1. 实例化构造函数 Hook
  2. 注册(一次或者多次)
  3. 执行(传入参数)
  4. 如果有需要还可以增加对整个流程(包括注册和执行)的监听-拦截器

以最简单的 SyncHook 为例:

  1. // 简单来说就是实例化 Hooks 类 
  2. // 接收一个可选参数,参数是一个参数名的字符串数组 
  3. const hook = new SyncHook(["arg1""arg2""arg3"]); 
  4. // 注册 
  5. // 第一个入参为注册名 
  6. // 第二个为注册回调方法 
  7. hook.tap("1", (arg1, arg2, arg3) => { 
  8.   console.log(1, arg1, arg2, arg3); 
  9.   return 1; 
  10. }); 
  11. hook.tap("2", (arg1, arg2, arg3) => { 
  12.   console.log(2, arg1, arg2, arg3); 
  13.   return 2; 
  14. }); 
  15. hook.tap("3", (arg1, arg2, arg3) => { 
  16.   console.log(3, arg1, arg2, arg3); 
  17.   return 3; 
  18. }); 
  19. // 执行 
  20. // 执行顺序则是根据这个实例类型来决定的 
  21. hook.call("a""b""c"); 
  22.  
  23. //------输出------ 
  24. // 先注册先触发 
  25. 1 a b c 
  26. 2 a b c 
  27. 3 a b c 

上面的例子为同步的情况,若注册异步则:

  1. let { AsyncSeriesHook } = require("tapable"); 
  2. let queue = new AsyncSeriesHook(["name"]); 
  3. console.time("cost"); 
  4. queue.tapPromise("1"function (name) { 
  5.   return new Promise(function (resolve) { 
  6.     setTimeout(function () { 
  7.       console.log(1, name); 
  8.       resolve(); 
  9.     }, 1000); 
  10.   }); 
  11. }); 
  12. queue.tapPromise("2"function (name) { 
  13.   return new Promise(function (resolve) { 
  14.     setTimeout(function () { 
  15.       console.log(2, name); 
  16.       resolve(); 
  17.     }, 2000); 
  18.   }); 
  19. }); 
  20. queue.tapPromise("3"function (name) { 
  21.   return new Promise(function (resolve) { 
  22.     setTimeout(function () { 
  23.       console.log(3, name); 
  24.       resolve(); 
  25.     }, 3000); 
  26.   }); 
  27. }); 
  28. queue.promise("weiyi").then((data) => { 
  29.   console.log(data); 
  30.   console.timeEnd("cost"); 
  31. }); 

HookMap 类使用

A HookMap is a helper class for a Map with Hooks

官方推荐将所有的钩子实例化在一个类的属性 hooks 上,如:

  1. class Car { 
  2.  constructor() { 
  3.   this.hooks = { 
  4.    accelerate: new SyncHook(["newSpeed"]), 
  5.    brake: new SyncHook(), 
  6.    calculateRoutes: new AsyncParallelHook(["source""target""routesList"]) 
  7.   }; 
  8.  } 
  9.  /* ... */ 
  10.  setSpeed(newSpeed) { 
  11.   // following call returns undefined even when you returned values 
  12.   this.hooks.accelerate.call(newSpeed); 
  13.  } 

注册&执行:

  1. const myCar = new Car(); 
  2.  
  3. myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`)); 
  4.  
  5. myCar.setSpeed(1) 

而 HookMap 正是这种推荐写法的一个辅助类。具体使用方法:

  1. const keyedHook = new HookMap(key => new SyncHook(["arg"])) 
  2.  
  3. keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ }); 
  4. keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ }); 
  5. keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ }); 
  6.  
  7. const hook = keyedHook.get("some-key"); 
  8. if(hook !== undefined) { 
  9.  hook.callAsync("arg", err => { /* ... */ }); 

MultiHook 类使用

A helper Hook-like class to redirect taps to multiple other hooks

相当于提供一个存放一个 hooks 列表的辅助类:

  1. const { MultiHook } = require("tapable"); 
  2.  
  3. this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]); 

Tapable 的原理

核心就是通过 Hook 来进行注册的回调存储和触发,通过 HookCodeFactory 来控制注册的执行流程。

首先来观察一下 tapable 的 lib 文件结构,核心的代码都是存放在 lib 文件夹中。其中 index.js 为所有可使用类的入口。Hook 和 HookCodeFactory 则是核心类,主要的作用就是注册和触发流程。还有两个辅助类 HookMap 和 MultiHook 以及一个工具类 util-browser。其余均是以 Hook 和 HookCodeFactory 为基础类衍生的以上分类所提及的 9 种 Hooks。整个结构是非常简单清楚的。如图所示:

接下来讲一下最重要的两个类,也是 tapable 的源码核心。

Hook

首先看 Hook 的属性,可以看到属性中有熟悉的注册的方法:tap、tapAsync、tapPromise。执行方法:call、promise、callAsync。以及存放所有的注册项 taps。constructor 的入参就是每个钩子实例化时的入参。从属性上就能够知道是 Hook 类为继承它的子类提供了最基础的注册和执行的方法

  1. class Hook { 
  2.  constructor(args = [], name = undefined) { 
  3.   this._args = args; 
  4.   this.name = name
  5.   this.taps = []; 
  6.   this.interceptors = []; 
  7.   this._call = CALL_DELEGATE; 
  8.   this.call = CALL_DELEGATE; 
  9.   this._callAsync = CALL_ASYNC_DELEGATE; 
  10.   this.callAsync = CALL_ASYNC_DELEGATE; 
  11.   this._promise = PROMISE_DELEGATE; 
  12.   this.promise = PROMISE_DELEGATE; 
  13.   this._x = undefined; 
  14.  
  15.   this.compile = this.compile; 
  16.   this.tap = this.tap; 
  17.   this.tapAsync = this.tapAsync; 
  18.   this.tapPromise = this.tapPromise; 
  19.  } 
  20.  ... 

那么 Hook 类是如何收集注册项的?如代码所示:

  1. class Hook { 
  2.  ... 
  3.  tap(options, fn) { 
  4.   this._tap("sync", options, fn); 
  5.  } 
  6.  
  7.  tapAsync(options, fn) { 
  8.   this._tap("async", options, fn); 
  9.  } 
  10.  
  11.  tapPromise(options, fn) { 
  12.   this._tap("promise", options, fn); 
  13.  } 
  14.  
  15.  _tap(type, options, fn) { 
  16.   if (typeof options === "string") { 
  17.    options = { 
  18.     name: options.trim() 
  19.    }; 
  20.   } else if (typeof options !== "object" || options === null) { 
  21.    throw new Error("Invalid tap options"); 
  22.   } 
  23.   if (typeof options.name !== "string" || options.name === "") { 
  24.    throw new Error("Missing name for tap"); 
  25.   } 
  26.   if (typeof options.context !== "undefined") { 
  27.    deprecateContext(); 
  28.   } 
  29.   // 合并参数 
  30.   options = Object.assign({ type, fn }, options); 
  31.   // 执行注册的 interceptors 的 register 监听,并返回执行后的 options 
  32.   options = this._runRegisterInterceptors(options); 
  33.   // 收集到 taps 中 
  34.   this._insert(options); 
  35.  } 
  36.  _runRegisterInterceptors(options) { 
  37.   for (const interceptor of this.interceptors) { 
  38.    if (interceptor.register) { 
  39.     const newOptions = interceptor.register(options); 
  40.     if (newOptions !== undefined) { 
  41.      options = newOptions; 
  42.     } 
  43.    } 
  44.   } 
  45.   return options; 
  46.  } 
  47.  ... 

可以看到三种注册的方法都是通过_tap 来实现的,只是传入的 type 不同。_tap 主要做了两件事。

  1. 执行 interceptor.register,并返回 options
  2. 收集注册项到 this.taps 列表中,同时根据 stage 和 before 排序。(stage 和 before 是注册时的可选参数)

收集完注册项,接下来就是执行这个流程:

  1. const CALL_DELEGATE = function(...args) { 
  2.  this.call = this._createCall("sync"); 
  3.  return this.call(...args); 
  4. }; 
  5. const CALL_ASYNC_DELEGATE = function(...args) { 
  6.  this.callAsync = this._createCall("async"); 
  7.  return this.callAsync(...args); 
  8. }; 
  9. const PROMISE_DELEGATE = function(...args) { 
  10.  this.promise = this._createCall("promise"); 
  11.  return this.promise(...args); 
  12. }; 
  13. class Hook { 
  14.  constructor() { 
  15.   ... 
  16.   this._call = CALL_DELEGATE; 
  17.   this.call = CALL_DELEGATE; 
  18.   this._callAsync = CALL_ASYNC_DELEGATE; 
  19.   this.callAsync = CALL_ASYNC_DELEGATE; 
  20.   this._promise = PROMISE_DELEGATE; 
  21.   this.promise = PROMISE_DELEGATE; 
  22.   ... 
  23.  } 
  24.  compile(options) { 
  25.   throw new Error("Abstract: should be overridden"); 
  26.  } 
  27.  
  28.  _createCall(type) { 
  29.   return this.compile({ 
  30.    taps: this.taps, 
  31.    interceptors: this.interceptors, 
  32.    args: this._args, 
  33.    type: type 
  34.   }); 
  35.  } 

执行流程可以说是殊途同归,最后都是通过_createCall 来返回一个 compile 执行后的值。从上文可知,tapable 的执行流程有同步,异步串行,异步并行、循环等,因此 Hook 类只提供了一个抽象方法 compile,那么 compile 具体是怎么样的呢。这就引出了下一个核心类 HookCodeFactory。

HookCodeFactory

见名知意,该类是一个返回 hookCode 的工厂。首先来看下这个工厂是如何被使用的。这是其中一种 hook 类 AsyncSeriesHook 使用方式:

  1. const HookCodeFactory = require("./HookCodeFactory"); 
  2.  
  3. class AsyncSeriesHookCodeFactory extends HookCodeFactory { 
  4.  content({ onError, onDone }) { 
  5.   return this.callTapsSeries({ 
  6.    onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), 
  7.    onDone 
  8.   }); 
  9.  } 
  10.  
  11. const factory = new AsyncSeriesHookCodeFactory(); 
  12. // options = { 
  13. //   taps: this.taps, 
  14. //   interceptors: this.interceptors, 
  15. //   args: this._args, 
  16. //   type: type 
  17. // } 
  18. const COMPILE = function(options) { 
  19.  factory.setup(this, options); 
  20.  return factory.create(options); 
  21. }; 
  22.  
  23. function AsyncSeriesHook(args = [], name = undefined) { 
  24.  const hook = new Hook(args, name); 
  25.  hook.constructor = AsyncSeriesHook; 
  26.  hook.compile = COMPILE; 
  27.  ... 
  28.  return hook; 

HookCodeFactory 的职责就是将执行代码赋值给 hook.compile,从而使 hook 得到执行能力。来看看该类内部运转逻辑是这样的:

  1. class HookCodeFactory { 
  2.  constructor(config) { 
  3.   this.config = config; 
  4.   this.options = undefined; 
  5.   this._args = undefined; 
  6.  } 
  7.  ... 
  8.  create(options) { 
  9.   ... 
  10.   this.init(options); 
  11.   // type 
  12.   switch (this.options.type) { 
  13.    case "sync": fn = new Function(省略...);break; 
  14.    case "async": fn = new Function(省略...);break; 
  15.    case "promise": fn = new Function(省略...);break; 
  16.   } 
  17.   this.deinit(); 
  18.   return fn; 
  19.  } 
  20.  init(options) { 
  21.   this.options = options; 
  22.   this._args = options.args.slice(); 
  23.  } 
  24.  
  25.  deinit() { 
  26.   this.options = undefined; 
  27.   this._args = undefined; 
  28.  } 

最终返回给 compile 就是 create 返回的这个 fn,fn 则是通过 new Function()进行创建的。那么重点就是这个 new Function 中了。

先了解一下 new Function 的语法

new Function ([arg1[, arg2[, ...argN]],] functionBody)

  • arg1, arg2, ... argN:被函数使用的参数的名称必须是合法命名的。参数名称是一个有效的 JavaScript 标识符的字符串,或者一个用逗号分隔的有效字符串的列表;例如“×”,“theValue”,或“a,b”。
  • functionBody:一个含有包括函数定义的 JavaScript 语句的字符串。

基本用法:

  1. const sum = new Function('a''b''return a + b'); 
  2. console.log(sum(2, 6)); 
  3. // expected output: 8 

使用 Function 构造函数的方法:

  1. class HookCodeFactory { 
  2.  create() { 
  3.   ... 
  4.   fn = new Function(this.args({...}), code) 
  5.   ... 
  6.   return fn 
  7.  } 
  8.  args({ before, after } = {}) { 
  9.   let allArgs = this._args; 
  10.   if (before) allArgs = [before].concat(allArgs); 
  11.   if (after) allArgs = allArgs.concat(after); 
  12.   if (allArgs.length === 0) { 
  13.    return ""
  14.   } else { 
  15.    return allArgs.join(", "); 
  16.   } 
  17.  } 

这个 this.args()就是返回执行时传入参数名,为后面 code 提供了对应参数值。

  1. fn = new Function
  2.  this.args({...}),  
  3.  '"use strict";\n' + 
  4.   this.header() + 
  5.   this.contentWithInterceptors({ 
  6.    onError: err => `throw ${err};\n`, 
  7.    onResult: result => `return ${result};\n`, 
  8.    resultReturns: true
  9.    onDone: () => ""
  10.    rethrowIfPossible: true 
  11.   }) 
  12. header() { 
  13.  let code = ""
  14.  if (this.needContext()) { 
  15.   code += "var _context = {};\n"
  16.  } else { 
  17.   code += "var _context;\n"
  18.  } 
  19.  code += "var _x = this._x;\n"
  20.  if (this.options.interceptors.length > 0) { 
  21.   code += "var _taps = this.taps;\n"
  22.   code += "var _interceptors = this.interceptors;\n"
  23.  } 
  24.  return code; 
  25.  
  26. contentWithInterceptors() { 
  27.  // 由于代码过多这边描述一下过程 
  28.  // 1. 生成监听的回调对象如: 
  29.  // { 
  30.  //  onError, 
  31.  //  onResult, 
  32.  //  resultReturns, 
  33.  //  onDone, 
  34.  //  rethrowIfPossible 
  35.  // } 
  36.   // 2. 执行 this.content({...}),入参为第一步返回的对象 
  37.  ... 

而对应的 functionBody 则是通过 header 和 contentWithInterceptors 共同生成的。this.content 则是根据钩子类型的不同调用不同的方法如下面代码则调用的是 callTapsSeries:

  1. class SyncHookCodeFactory extends HookCodeFactory { 
  2.  content({ onError, onDone, rethrowIfPossible }) { 
  3.   return this.callTapsSeries({ 
  4.    onError: (i, err) => onError(err), 
  5.    onDone, 
  6.    rethrowIfPossible 
  7.   }); 
  8.  } 

HookCodeFactory 有三种生成 code 的方法:

  1. // 串行 
  2. callTapsSeries() {...} 
  3. // 循环 
  4. callTapsLooping() {...} 
  5. // 并行 
  6. callTapsParallel() {...} 
  7. // 执行单个注册回调,通过判断 sync、async、promise 返回对应 code 
  8. callTap() {...} 
  1. 并行(Parallel)原理:并行的情况只有在异步的时候才发生,因此执行所有的 taps 后,判断计数器是否为 0,为 0 则执行结束回调(计数器为 0 有可能是因为 taps 全部执行完毕,有可能是因为返回值不为 undefined,手动设置为 0)
  2. 循环(Loop)原理:生成 do{}while(__loop)的代码,将执行后的值是否为 undefined 赋值给_loop,从而来控制循环
  3. 串行:就是按照 taps 的顺序来生成执行的代码
  4. callTap:执行单个注册回调
  • sync:按照顺序执行
  1. var _fn0 = _x[0]; 
  2. _fn0(arg1, arg2, arg3); 
  3. var _fn1 = _x[1]; 
  4. _fn1(arg1, arg2, arg3); 
  5. var _fn2 = _x[2]; 
  6. _fn2(arg1, arg2, arg3); 
  • async 原理:将单个 tap 封装成一个_next[index]函数,当前一个函数执行完成即调用了 callback,则会继续执行下一个_next[index]函数,如生成如下 code:
  1. function _next1() { 
  2.   var _fn2 = _x[2]; 
  3.   _fn2(name, (function (_err2) { 
  4.     if (_err2) { 
  5.       _callback(_err2); 
  6.     } else { 
  7.       _callback(); 
  8.     } 
  9.   })); 
  10.  
  11. function _next0() { 
  12.   var _fn1 = _x[1]; 
  13.   _fn1(name, (function (_err1) { 
  14.     if (_err1) { 
  15.       _callback(_err1); 
  16.     } else { 
  17.       _next1(); 
  18.     } 
  19.   })); 
  20. var _fn0 = _x[0]; 
  21. _fn0(name, (function (_err0) { 
  22.   if (_err0) { 
  23.     _callback(_err0); 
  24.   } else { 
  25.     _next0(); 
  26.   } 
  27. })); 
  • promise:将单个 tap 封装成一个_next[index]函数,当前一个函数执行完成即调用了 promise.then(),then 中则会继续执行下一个_next[index]函数,如生成如下 code:
  1. function _next1() { 
  2.   var _fn2 = _x[2]; 
  3.   var _hasResult2 = false
  4.   var _promise2 = _fn2(name); 
  5.   if (!_promise2 || !_promise2.then
  6.     throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise2 + ')'); 
  7.   _promise2.then((function (_result2) { 
  8.     _hasResult2 = true
  9.     _resolve(); 
  10.   }), function (_err2) { 
  11.     if (_hasResult2) throw _err2; 
  12.     _error(_err2); 
  13.   }); 
  14.  
  15. function _next0() { 
  16.   var _fn1 = _x[1]; 
  17.   var _hasResult1 = false
  18.   var _promise1 = _fn1(name); 
  19.   if (!_promise1 || !_promise1.then
  20.     throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise1 + ')'); 
  21.   _promise1.then((function (_result1) { 
  22.     _hasResult1 = true
  23.     _next1(); 
  24.   }), function (_err1) { 
  25.     if (_hasResult1) throw _err1; 
  26.     _error(_err1); 
  27.   }); 
  28. var _fn0 = _x[0]; 
  29. var _hasResult0 = false
  30. var _promise0 = _fn0(name); 
  31. if (!_promise0 || !_promise0.then
  32.   throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise0 + ')'); 
  33. _promise0.then((function (_result0) { 
  34.   _hasResult0 = true
  35.   _next0(); 
  36. }), function (_err0) { 
  37.   if (_hasResult0) throw _err0; 
  38.   _error(_err0); 
  39. }); 

将以上的执行顺序以及执行方式来进行组合,就得到了现在的 9 种 Hook 类。若后续需要更多的模式只需要增加执行顺序或者执行方式就能够完成拓展。

如图所示:

如何助力 webpack

插件可以使用 tapable 对外暴露的方法向 webpack 中注入自定义构建的步骤,这些步骤将在构建过程中触发。

webpack 将整个构建的步骤生成一个一个 hook 钩子(即 tapable 的 9 种 hook 类型的实例),存储在 hooks 的对象里。插件可以通过 Compiler 或者 Compilation 访问到对应的 hook 钩子的实例,进行注册(tap,tapAsync,tapPromise)。当 webpack 执行到相应步骤时就会通过 hook 来进行执行(call, callAsync,promise),从而执行注册的回调。以 ConsoleLogOnBuildWebpackPlugin 自定义插件为例:

  1. const pluginName = 'ConsoleLogOnBuildWebpackPlugin'
  2.  
  3. class ConsoleLogOnBuildWebpackPlugin { 
  4.   apply(compiler) { 
  5.     compiler.hooks.run.tap(pluginName, (compilation) => { 
  6.       console.log('webpack 构建过程开始!'); 
  7.     }); 
  8.   } 
  9.  
  10. module.exports = ConsoleLogOnBuildWebpackPlugin; 

可以看到在 apply 中通过 compiler 的 hooks 注册(tap)了在 run 阶段时的回调。从 Compiler 类中可以了解到在 hooks 对象中对 run 属性赋值 AsyncSeriesHook 的实例,并在执行的时候通过 this.hooks.run.callAsync 触发了已注册的对应回调:

  1. class Compiler { 
  2.  constructor(context) { 
  3.   this.hooks = Object.freeze({ 
  4.     ... 
  5.     run: new AsyncSeriesHook(["compiler"]), 
  6.     ... 
  7.   }) 
  8.  } 
  9.  run() { 
  10.   ... 
  11.   const run = () => { 
  12.    this.hooks.beforeRun.callAsync(this, err => { 
  13.     if (err) return finalCallback(err); 
  14.  
  15.     this.hooks.run.callAsync(this, err => { 
  16.      if (err) return finalCallback(err); 
  17.  
  18.      this.readRecords(err => { 
  19.       if (err) return finalCallback(err); 
  20.  
  21.       this.compile(onCompiled); 
  22.      }); 
  23.     }); 
  24.    }); 
  25.   }; 
  26.   ... 
  27.  } 

如图所示,为该自定义插件的执行过程:

总结

  1. tapable 对外暴露 9 种 hook 钩子,核心方法是注册、执行、拦截器
  2. tapable 实现方式就是根据钩子类型以及注册类型来拼接字符串传入 Function 构造函数创建一个新的 Function 对象
  3. webpack 通过 tapable 来对整个构建步骤进行了流程化的管理。实现了对每个构建步骤都能进行灵活定制化需求。

参考资料

[1]webpack 官方文档中对于 plugin 的介绍:

https://webpack.docschina.org/concepts/plugins/

[2]tapable 相关介绍:

http://www.zhufengpeixun.com/grow/html/103.7.webpack-tapable.html

[3]tabpable 源码:

https://github.com/webpack/tapable

[4]webpack 源码:

https://github.com/webpack/webpack

 

责任编辑:姜华 来源: 微医大前端技术
相关推荐

2011-08-23 09:52:31

CSS

2015-11-18 14:14:11

OPNFVNFV

2014-07-30 10:55:27

2016-11-03 13:33:31

2016-11-08 19:19:06

2013-05-23 16:23:42

Windows Azu微软公有云

2014-07-21 12:57:25

诺基亚微软裁员

2016-12-29 18:21:01

2014-07-15 10:31:07

asyncawait

2012-05-18 16:54:21

FedoraFedora 17

2019-06-04 09:00:07

Jenkins X开源开发人员

2016-12-29 13:34:04

阿尔法狗围棋计算机

2019-08-05 10:08:25

软件操作系统程序员

2015-06-11 11:10:09

对象存储云存储

2011-05-13 09:43:27

产品经理PM

2013-11-14 16:03:23

Android设计Android Des

2022-11-07 14:23:35

RPA人工智能流程自动化管理

2021-04-15 07:01:28

区块链分布式DLT

2019-04-28 09:34:06

2018-08-08 14:37:53

显卡虚拟化3D
点赞
收藏

51CTO技术栈公众号