代码改变世界

如何编写一个gulp插件

2017-02-06 22:44  猴子猿  阅读(1832)  评论(0编辑  收藏  举报

很久以前,我们在"细说gulp"随笔中,以压缩JavaScript为例,详细地讲解了如何利用gulp来完成前端自动化。

再来短暂回顾下,当时除了借助gulp之外,我们还利用了第三方gulp插件”gulp-uglify”,来达到压缩JavaScript文件的目的。

代码如下:

今儿,我们的重点就是,自己也来实现一个gulp插件。

正文

其实,如果只是单纯地想要编写一个gulp插件不难,可以借助through2或者through-gulp来编写(through-gulp是基于through2开发的)。

例如,我们想要接下来即将编写的插件(暂取名为modify),实现这样的功能:将指定html文件中的{{…}},全部替换成’Monkey 2 Dorie’。

如下:

下面我们将利用through2以及through-gulp一一道来。

**through2**

'use strict'
var through2 = require('through2');
module.exports = modify;
function modify(){
    return through2.obj(function(file, encoding, cb){
        //如果文件为空,不做任何操作,转入下一个操作,即下一个pipe
        if(file.isNull()){
            console.log('isNull');
            this.push(file);
            return cb();
        }
        //插件不支持对stream直接操作,抛出异常
        if(file.isStream()){
            console.log('isStream');
            this.emit('error');
            return cb();
        }
        //内容转换,处理好后,再转成Buffer形式
        var content = versionFun(file.contents.toString());
        file.contents = new Buffer(content);
        //下面这两句基本是标配,可参考through2的API
        this.push(file);
        cb();
    });
}
function versionFun(data){
    return data.replace(/{{something}}/, ' Monkey 2 Dorie ');
}

**through-gulp**

'use strict'
var through = require('through-gulp');
module.exports = modify;
function modify(){
    var stream = through(function(file, encoding, callback){
        //如果文件为空,不做任何操作,转入下一个操作,即下一个pipe
        if(file.isNull()){
            console.log('file is null!');
            this.push(file);
            return callback();    
        }
        //插件不支持对stream直接操作,抛出异常
        if(file.isStream()){
            console.log('file is stream!');
            this.emit('error');
            return callback();    
        }
        //内容转换,处理好后,再转成Buffer形式
        var content = versionFun(file.contents.toString('utf-8'));
        file.contents = new Buffer(content, 'utf-8');
        this.push(file);
        callback();
    }, function(callback){
        console.log('处理完毕!');
        callback();
    });
    return stream;
}
function versionFun(data){
    return data.replace(/{{something}}/, ' Monkey 2 Dorie ');
}

详情代码见github.

拓展阅读

[1]、through-gulp

[2]、gulp规范

[3]、gulp高级技巧