tapable
webpack本质上是一种事件流的机制,他的工作流程就是将各个插件串联起来,而实现这一切的核心就是tapable,
tapable有点类似于nodejs的events库,核心原理也是依赖于发布订阅模式:
继承了很多插件,同步的和异步的
tapable库中有3中注册方法 tap(同步注册)、tabAsync(回调cb)、tabPromise(注册是promise)
调用的三种方法 call、 callAsync、 promise
SyncHook
作用: 让添加的钩子按顺序执行
使用方式:
let {
SyncHook} = require('tapable');
class Lesson {
constructor() {
this.hooks = {
arch: new SyncHook(['name']),
}
}
// 注册监听函数
tap() {
this.hooks.arch.tap('node', function(name) {
console.log('node', name);
});
this.hooks.arch.tap('react', function(name) {
console.log('react', name);
});
}
start() {
this.hooks.arch.call('zhangfeng');
}
}
let les = new Lesson();
les.tap(); // 注册这两个事件
les.start(); // 启动钩子
实现原理:
class SyncHook {
// 钩子是同步的
constructor(args) {
// args => ['name']
this.tasks = [];
}
call(...args) {
this.tasks.forEach(task => task(...args));
}
tap(name, task) {
this.tasks.push(task);
}
}
let hook = new SyncHook(['name']);
hook.tap('react', function (name) {
console.log('react'