gulp源码分析
一.整体结构分析
整体结构
通过在nodejs环境对源码的打印,我们最终得到的gulp实例行如下图。那么我们gulp实例上的属性和方法是如何生成的呢?
Gulp { domain: null, _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, _registry: DefaultRegistry { _tasks: {} }, _settle: false, watch: [Function: bound ], task: [Function: bound task], series: [Function: bound series], parallel: [Function: bound parallel], registry: [Function: bound registry], tree: [Function: bound tree], lastRun: [Function: bound lastRun], src: [Function: bound src], dest: [Function: bound dest], symlink: [Function: bound symlink] }
(1)类的实现
源码index.js分为三个部分,第一部分是gulp构造函数,添加实例方法,第二部分是Gulp原型方法添加,第三部分是导出gulp实例。
//第一部分是gulp构造函数,添加实例方法function Gulp(){ .......
} //第二部分是原型方法添加Gulp.prototype.src=....... //第三部分是导出gulp实例Gulp.prototype.Gulp = Gulp; var inst = new Gulp(); module.exports = inst;
我们知道实现一个类,通过构造函数往this对象添加实例属性和方法,或者添加原型方法,类的实例自动拥有实例属性、实例方法和原型方法。
//People类function People () { this.name = "Yorhom"; } People.prototype.getName = function () { console.log(this.name);// "Yorhom"}; var yorhom = new People(); yorhom.getName() console.log(yorhom.name)// "Yorhom"
所以我们在构造函数中this对象定义的watch等10个方法具体指的哪些方法呢?其实它包括util.inherits(Gulp, Undertaker); 实现了undertaker原型方法tree()、task()、series()、lastRun()、parallel()、registry()的继承,然后通过prototype定义了src()、dest()、symlink()、watch()。最后要说的是 Undertaker.call(this); ,它通过Call继承实现了对Undertaker实例属性_registry和_settle
//https://github.com/gulpjs/undertaker,index.jsfunction Undertaker(customRegistry) { EventEmitter.call(this); this._registry = new DefaultRegistry(); if (customRegistry) { this.registry(customRegistry); } this._settle = (process.env.UNDERTAKER_SETTLE === 'true'); } inherits(Undertaker, EventEmitter); Undertaker.prototype.tree = tree; Undertaker.prototype.task = task; Undertaker.prototype.series = series; Undertaker.prototype.lastRun = lastRun; Undertaker.prototype.parallel = parallel; Undertaker.prototype.registry =