好久之前,咱们在"细说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高级技巧