webpack——tapable

tapable版本1.3
tabpable可以为插件提供一系列的钩子函数,

const {
    SyncHook,
    SyncBailHook,
    SyncWaterfallHook,
    SyncLoopHook,
    AsyncParallelHook,
    AsyncParallelBailHook,
    AsyncSeriesHook,
    AsyncSeriesBailHook,
    AsyncSeriesWaterfallHook 
 } = require("tapable");

以SyncHook为例,在tap过程中的调用过程为tap -> _insert
在call过程中的调用过程为call -> lazyCompileHook -> compile -> factory.setup -> factory.create

  1. tap过程中主要为订阅过程,将function挂载到taps上
  2. call过程通过factory工厂函数,将同步事件合成code码,执行code从而实现同步事件。

tap

该方法主要是对option进行处理, 如在syncHook中会将type设置为sync;
执行interceptors拦截器register方法, 并将拦截器的返回值作为新的options。

tap(options, fn) {
        if (typeof options === "string") options = { name: options };
        if (typeof options !== "object" || options === null)
            throw new Error(
                "Invalid arguments to tap(options: Object, fn: function)"
            );
        options = Object.assign({ type: "sync", fn: fn }, options);
        if (typeof options.name !== "string" || options.name === "")
            throw new Error("Missing name for tap");
        options = this._runRegisterInterceptors(options);
        this._insert(options);
    }
_runRegisterInterceptors(options) {
    for (const interceptor of this.interceptors) {
        if (interceptor.register) {
            const newOptions = interceptor.register(options);
            if (newOptions !== undefined) options = newOptions;
        }
    }
    return options;
}  

_insert

按照优先级的方式查到到tap事件所需要插入的位置, 然后进行插入。

_insert(item) {
    this._resetCompilation();
    let before;
    if (typeof item.before === "string") before = new Set([item.before]);
    else if (Array.isArray(item.before)) {
        before = new Set(item.before);
    }
    let stage = 0;
    if (typeof item.stage === "number") stage = item.stage;
    let i = this.taps.length;
    while (i > 0) {
        i--;
        const x = this.taps[i];
        this.taps[i + 1] = x;
        const xStage = x.stage || 0;
        if (before) {
            if (before.has(x.name)) {
                before.delete(x.name);
                continue;
            }
            if (before.size > 0) {
                continue;
            }
        }
        if (xStage > stage) {
            continue;
        }
        i++;
        break;
    }
    this.taps[i] = item;
}

compile

hooks最终通过factory.create实现实时生成code, 并执行。
factory.create是一个比较有意思的过程, 它并不像我当时猜想的通过迭代方案去实现事件的调用, 而是将事件列表进行code拼接而实现。 下面会对几种方法生成的code进行查看解说。

function createCompileDelegate(name, type) {
    return function lazyCompileHook(...args) {
        this[name] = this._createCall(type);
        return this[name](...args);
    };
}
...
_createCall(type) {
        return this.compile({
            taps: this.taps,
            interceptors: this.interceptors,
            args: this._args,
            type: type
        });
    }
...
compile(options) {
        factory.setup(this, options);
        return factory.create(options);
    }    

SyncHook

同步事件, 查看其code码, 它就是将taps列表中的事件顺序执行。

class Car {
    constructor() {
        this.hooks = {
            accelerate: new SyncHook(["newSpeed"]),
            brake: new SyncHook(),
            calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]),
            seriesWater: new AsyncSeriesWaterfallHook(['haha']),
            other: new AsyncSeriesWaterfallHook(['other'])
        };
    }
 
    /* ... */
}
let myCar = new Car();
myCar.hooks.brake.tap('test', () => {
    console.log('sync one')
})
myCar.hooks.brake.tap('test', () => {
    console.log('sync tow')
})

myCar.hooks.brake.call();

// 转为函数
ƒ anonymous(
) {
"use strict";
var _context;
var _x = this._x;
var _fn0 = _x[0];
_fn0();
var _fn1 = _x[1];
_fn1();

}

AsyncParallelHook

异步并行事件, 同时执行taps上的包装函数, 使用_counter计数, 完成后执行最后的回调。

myCar.hooks.calculateRoutes.tapAsync('test', (source, target,  cb) => {
    setTimeout(function () {   
        console.log('asycn paralle one')
        cb()
    }, 1000) 
})
myCar.hooks.calculateRoutes.tapAsync('test', (source, target, cb) => {
    setTimeout(function () {
        console.log('asycn paralle two')
        cb()
    }, 0) 
})
myCar.hooks.calculateRoutes.callAsync('async paralle', 'lalal', function () {
    console.log('has finished')
})
...
(function anonymous(source, target, _callback
) {
    "use strict";
    var _context;
    var _x = this._x;
    do {
        var _counter = 2;
        var _done = () => {
            _callback();
        };
        if (_counter <= 0) break;
        var _fn0 = _x[0];
        _fn0(source, target, _err0 => {
            if (_err0) {
                if (_counter > 0) {
                    _callback(_err0);
                    _counter = 0;
                }
            } else {
                if (--_counter === 0) _done();
            }
        });
        if (_counter <= 0) break;
        var _fn1 = _x[1];
        _fn1(source, target, _err1 => {
            if (_err1) {
                if (_counter > 0) {
                    _callback(_err1);
                    _counter = 0;
                }
            } else {
                if (--_counter === 0) _done();
            }
        });
    } while (false);

})

AsyncParallelHook & promise

异步并行事件, promise方式

myCar.hooks.calculateRoutes.tapPromise('test', () => {
    return new Promise(function (resolve, reject){
        resolve('promise one')
    })
})
myCar.hooks.calculateRoutes.tapPromise('test', () => {
    return new Promise(function (resolve, reject){
        resolve('promise two')
    })
})
myCar.hooks.calculateRoutes.promise('paralle promise').then(function () {
    console.log('has finished')
});
(function anonymous(source, target, routesList, _callback
) {
    "use strict";
    var _context;
    var _x = this._x;
    do {
        var _counter = 2;
        var _done = () => {
            _callback();
        };
        if (_counter <= 0) break;
        var _fn0 = _x[0];
        var _hasResult0 = false;
        var _promise0 = _fn0(source, target, routesList);
        if (!_promise0 || !_promise0.then)
            throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise0 + ')');
        _promise0.then(_result0 => {
            _hasResult0 = true;
            if (--_counter === 0) _done();
        }, _err0 => {
            if (_hasResult0) throw _err0;
            if (_counter > 0) {
                _callback(_err0);
                _counter = 0;
            }
        });
        if (_counter <= 0) break;
        var _fn1 = _x[1];
        var _hasResult1 = false;
        var _promise1 = _fn1(source, target, routesList);
        if (!_promise1 || !_promise1.then)
            throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise1 + ')');
        _promise1.then(_result1 => {
            _hasResult1 = true;
            if (--_counter === 0) _done();
        }, _err1 => {
            if (_hasResult1) throw _err1;
            if (_counter > 0) {
                _callback(_err1);
                _counter = 0;
            }
        });
    } while (false);
})

AsyncSeriesHook

异步串行事件, 等一个事件完成后再执行另一个

myCar.hooks.washing.tapPromise('test', (data) => {
    return new Promise(function (resolve, reject){
        console.log('one ' + data)
        resolve('promise one')
    })
})
myCar.hooks.washing.tapPromise('test', (data) => {
    return new Promise(function (resolve, reject){
        console.log('two ' + data)
        resolve('promise two')
    })
})
myCar.hooks.washing.promise('async series').then(function () {
    console.log('has finished');
});
...
(function anonymous(water
) {
    "use strict";
    return new Promise((_resolve, _reject) => {
        var _sync = true;
        function _error(_err) {
            if (_sync)
                _resolve(Promise.resolve().then(() => { throw _err; }));
            else
                _reject(_err);
        };
        var _context;
        var _x = this._x;
        function _next0() {
            var _fn1 = _x[1];
            var _hasResult1 = false;
            var _promise1 = _fn1(water);
            if (!_promise1 || !_promise1.then)
                throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise1 + ')');
            _promise1.then(_result1 => {
                _hasResult1 = true;
                _resolve();
            }, _err1 => {
                if (_hasResult1) throw _err1;
                _error(_err1);
            });
        }
        var _fn0 = _x[0];
        var _hasResult0 = false;
        var _promise0 = _fn0(water);
        if (!_promise0 || !_promise0.then)
            throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise0 + ')');
        _promise0.then(_result0 => {
            _hasResult0 = true;
            _next0();
        }, _err0 => {
            if (_hasResult0) throw _err0;
            _error(_err0);
        });
        _sync = false;
    });

})

AsyncSeriesWaterfallHook

异步瀑布流事件, 串行事件, 将事件的结果传入下一个事件。

myCar.hooks.seriesWater.tapAsync('test', (data, cb) => {
    console.log(data);
    cb(null, 'the first result')
})
myCar.hooks.seriesWater.tapAsync('test', (data, cb) => {
    console.log(data);
    cb(null, 'the second result')
})

myCar.hooks.seriesWater.callAsync('series', (err, val) => {
    console.log('finished ' + val)
})
(function anonymous(haha, _callback
) {
    "use strict";
    var _context;
    var _x = this._x;
    function _next0() {
        var _fn1 = _x[1];
        _fn1(haha, (_err1, _result1) => {
            if (_err1) {
                _callback(_err1);
            } else {
                if (_result1 !== undefined) {
                    haha = _result1;
                }
                _callback(null, haha);
            }
        });
    }
    var _fn0 = _x[0];
    _fn0(haha, (_err0, _result0) => {
        if (_err0) {
            _callback(_err0);
        } else {
            if (_result0 !== undefined) {
                haha = _result0;
            }
            _next0();
        }
    });

})

AsyncSeriesWaterfallHook & promise

异步瀑布流事件, promise版本。

myCar.hooks.other.tapPromise('test', (data) => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(data)
            resolve('first')
        }, 0)
    })
})

myCar.hooks.other.tapPromise('test', (data) => {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(data)
            resolve('second')
        }, 0)
    })
})
myCar.hooks.other.promise('water promise').then(function () {
    console.log('finished')
})
....
(function anonymous(other
) {
    "use strict";
    return new Promise((_resolve, _reject) => {
        var _sync = true;
        function _error(_err) {
            if (_sync)
                _resolve(Promise.resolve().then(() => { throw _err; }));
            else
                _reject(_err);
        };
        var _context;
        var _x = this._x;
        function _next0() {
            var _fn1 = _x[1];
            var _hasResult1 = false;
            var _promise1 = _fn1(other);
            if (!_promise1 || !_promise1.then)
                throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise1 + ')');
            _promise1.then(_result1 => {
                _hasResult1 = true;
                if (_result1 !== undefined) {
                    other = _result1;
                }
                _resolve(other);
            }, _err1 => {
                if (_hasResult1) throw _err1;
                _error(_err1);
            });
        }
        var _fn0 = _x[0];
        var _hasResult0 = false;
        var _promise0 = _fn0(other);
        if (!_promise0 || !_promise0.then)
            throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise0 + ')');
        _promise0.then(_result0 => {
            _hasResult0 = true;
            if (_result0 !== undefined) {
                other = _result0;
            }
            _next0();
        }, _err0 => {
            if (_hasResult0) throw _err0;
            _error(_err0);
        });
        _sync = false;
    });

})

你可能感兴趣的:(webpack——tapable)