为了演示流控制,简单实现了注入插件 gulp-aop
先看下 gulp-aop 注入插件的用法
gulp = require "gulp"
concat = require "gulp-concat"
aop = require "gulp-aop"
gulp.task "default", ->
gulp.src ["test/a.js", "test/b.js"]
.pipe concat "t.min.js"
.pipe aop
header: -> console.log 'Inject to the head'
footer: -> console.log 'Inject to the end'
.pipe gulp.dest "./test"
了解 gulp 流控制之前先了解下 nodeJS 的流
nodeJS 四种流
nodeJS里有四种类型的流:Readable,Writable,Duplex,Transform
Readable: 可读流
Writable: 可写流
Duplex: 双工流
Transform: 转换流
跟 Gulp 相关的主要是转换流
gulp 流控制一般用如下两种方式
流截获方式一:
var through = require('through-gulp');
module.exports = function () {
var stream = through(function(file, encoding, callback) {
var sourceStr = file.contents.toString();
// 这里可以对代码进行处理
file.contents = new Buffer(sourceStr);
// 再往管道中注入修改后的内容
this.push(file);
callback();
});
stream.on("end", function () {
// 这里可以做些收尾工作
});
return stream;
};
流截获方式二:
var through = require('through2');
var fs = require("fs");
module.exports = function (opt) {
var aopHeader = "(" + (opt.header || function(){}).toString() + "());";
var aopFooter = "(" + (opt.footer || function(){}).toString() + "());";
function bufferContents(file, encoding, callback) {
if (file.isNull()) {
this.push(file);
return callback();
}
if (file.isStream()) {
this.push(file);
return callback();
}
if (file.isBuffer()) {
file.contents = new Buffer(aopHeader + file.contents.toString('utf8') + aopFooter);
}
this.push(file);
callback();
}
function endStream(callback) {
// 这里可以做些收尾工作
callback();
}
return through.obj(bufferContents, endStream);
};
编写自己的 Gulp 插件,流控制是基础。