gulp是基于”流“的构建工具,上层流的输出就是下层流的输入,为了更好的支持链式操做,可使用through2或者map-stream这两个库来对node stream作一层包装javascript
这里,咱们就使用through2来定义一个简单的gulp插件示例:doSomething.jshtml
'use strict'; var through = require('through2'), module.exports = function(opt) { function doSomething(file, encoding, callback) { if (file.isNull()) { return callback(null, file); } if (file.isStream()) { return callback(createError(file, 'Streaming not supported')); } //do something file.contents = new Buffer("this is my stream");//这里咱们只是简单的改变了内容,实际上你能够你的自定义逻辑部分就在这里执行 callback(null, file); } return through.obj(doSomething); };
接下来,在调用的地方,就这么简单:java
var doSomething = require('./doSomething.js');//假设模块存放路径在当前文件夹下 gulp.src("./app.js") .pipe(uglify())//调用其它插件 .pipe(doSomething())//调用咱们刚刚定义的插件 .pipe(gulp.dest('./myStream.js'));//持久化到磁盘
PS:虽然自定义插件就这么简单,但实际上你须要了解Node Stream的API和gulp的工做原理,才能更深入的理解整个过程当中到底发生了些什么。node
尊重他人原创,转载请务必注明来自http://www.cnblogs.com/Raoh/p/4169426.htmlgulp