如何編寫一個gulp插件

好久之前,咱們在"細說gulp"隨筆中,以壓縮JavaScript爲例,詳細地講解了如何利用gulp來完成前端自動化。html

再來短暫回顧下,當時除了藉助gulp以外,咱們還利用了第三方gulp插件」gulp-uglify」,來達到壓縮JavaScript文件的目的。前端

代碼以下:node

今兒,咱們的重點就是,本身也來實現一個gulp插件。git

正文

其實,若是隻是單純地想要編寫一個gulp插件不難,能夠藉助through2或者through-gulp來編寫(through-gulp是基於through2開發的)。github

例如,咱們想要接下來即將編寫的插件(暫取名爲modify),實現這樣的功能:將指定html文件中的{{…}},所有替換成’Monkey 2 Dorie’。npm

以下:gulp

下面咱們將利用through2以及through-gulp一一道來。ide

**through2**ui

'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**this

'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高級技巧

相關文章
相關標籤/搜索