Webpack是目前基于React和Redux开发的应用的主要打包工具。我想使用Angular 2或其他框架开发的应用也有很多在使用Webpack。
本节流程如图:

现在正式进入打包流程,起步方法为run:
Compiler.prototype.run = (callback) => {
const startTime = Date.now();
const onCompiled = (err, compilation) => { /**/ };
this.applyPluginsAsync("before-run", this, err => {
if (err) return callback(err);
this.applyPluginsAsync("run", this, err => {
if (err) return callback(err);
this.readRecords(err => {
if (err) return callback(err);
this.compile(onCompiled);
});
});
});
}
为什么不介绍compiler对象?因为构造函数中并没有一个初始化的方法,只是普通的变量声明,没啥好讲的。
在run方法中,首先是调用了tapable的applyPluginsAsync执行了before-run事件流,该事件流的定义地点如下:
// NodeEnvironmentPlugin
compiler.plugin("before-run", (compiler, callback) => {
if (compiler.inputFileSystem === inputFileSystem)
inputFileSystem.purge();
callback();
});
在对compiler对象的文件系统方法的挂载插件中,注入了before-run这个事件流,这里首先看一下applyPluginsAsync(做了小幅度的修改以适应webpack源码):
// tapable
Tapable.prototype.applyPluginsAsync = (name, ...args, callback) => {
var plugins = this._plugins[name];
if (!plugins || plugins.length === 0) return callback();
var i = 0;
var _this = this;
// args为[args,next函数]
args.push(copyProperties(callback, function next(err) {
// 事件流出错或者全部执行完后调用回调函数
if (err) return callback(err);
i++;
if (i >= plugins.length) {
return callback();
}
// 执行下一个事件
plugins[i].apply(_this, args);
}));
// 执行第一个事件
plugins[0].apply(this, args);
};
当时在第八节没有讲这个系列的事件流触发方式,这里简单说下:
1、copyProperties用于对象属性的拷贝,类似于Object.assign,然而在这里传入的是两个函数,一点用都没有!!!!!(当时没写讲解就是因为一直卡在这个对象拷贝方法在这里有什么毛用)
2、在webpack中,args为一个this,指向compiler的上下文
3、注入该事件流的事件必须要执行callback方法(如上例),此时执行的并不是外部的callback,而是next函数
4、有两种情况下会执行外部callback,中途出错或者所有事件流执行完毕
这样就很明白了,注入before-run中的函数形参的意义如下:
内容版权声明:除非注明,否则皆为本站原创文章。
