zoukankan      html  css  js  c++  java
  • 如何编写一个gulp插件

    很久以前,我们在"细说gulp"随笔中,以压缩JavaScript为例,详细地讲解了如何利用gulp来完成前端自动化。

    再来短暂回顾下,当时除了借助gulp之外,我们还利用了第三方gulp插件”gulp-uglify”,来达到压缩JavaScript文件的目的。

    代码如下:

    今儿,我们的重点就是,自己也来实现一个gulp插件。

    正文

    其实,如果只是单纯地想要编写一个gulp插件不难,可以借助through2或者through-gulp来编写(through-gulp是基于through2开发的)。

    例如,我们想要接下来即将编写的插件(暂取名为modify),实现这样的功能:将指定html文件中的{{…}},全部替换成’Monkey 2 Dorie’。

    如下:

    下面我们将利用through2以及through-gulp一一道来。

    **through2**

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

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

  • 相关阅读:
    Ubuntu双系统
    Qt实现 动态化遍历二叉树(前中后层次遍历)
    Qt学习资料
    Qt学习--信号与槽(多窗口的实现)
    Qt 学习-----helloword
    二叉树的前中后层次遍历
    悬浮在网页右侧并可依次展开的菜单导航
    js实现仿华为手机计算器,兼容电脑和手机屏幕
    jquery json实现面向对象 百度十二星座
    knova绘制进度条
  • 原文地址:https://www.cnblogs.com/giggle/p/6344789.html
Copyright © 2011-2022 走看看