gulpthrough2

Apply another gulp plugin in my own gulp plugin using through2


I am writing my own gulp plugin which looks like this...

var through2 = require('through2');
var order = require('gulp-order');

module.exports = function() {
    return through2.obj(function(file, encoding, callback) {
        callback(null, transform(file));
    });
};

function transform(file) {
    // I will modify file.contents here - its ok
    return file;
}

and I would like to apply some other gulp plugin on my buffer which came from gulp.src. Is it possible using through2? For example before calling through2.obj() I would like to apply gulp-order plugin - how can I do this?


Solution

  • If you want to chain different gulp plugins together lazypipe is generally is good option:

    var through2 = require('through2');
    var order = require('gulp-order');
    
    function yourPlugin()
        return through2.obj(function(file, encoding, callback) {
            callback(null, transform(file));
        });
    }
    
    function transform(file) {
        // I will modify file.contents here - its ok
        return file;
    }
    
    function orderPlugin()
        return order(['someFolder/*.js', 'someOtherFolder/*.js']);
    }
    
    module.exports = function() {
       return lazypipe().pipe(orderPlugin).pipe(yourPlugin)();
    };