Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gulp使用5.编写gulp插件 #15

Open
damoclesX opened this issue Aug 18, 2015 · 0 comments
Open

gulp使用5.编写gulp插件 #15

damoclesX opened this issue Aug 18, 2015 · 0 comments

Comments

@damoclesX
Copy link
Owner

在用gulp处理某些任务时,一时半会儿找不到已有插件或者没有最适合的gulp插件,这时便可以尝试自己编写gulp插件

编写gulp插件一定要符合gulp插件的准则,只做一件事情,并且把它做得很好

假设我们需要编写一个gulp插件,来给css文件自动添加浏览器前缀,新建一个文件夹gulp-css-prefix。安装开发gulp插件需要用到的工具

npm install through2 gulp-util

新建index.js

var through = require('through2'),
    gutil = require('gulp-util'),
    PluginError = gutil.PluginError;

//声明插件名称
const PLUGIN_NAME = 'gulp-css-prefix';

//主要处理函数
function prefix(config){
    var stream = through.obj(function(file,enc,cb){
        //输出正在处理的文件路径
        gutil.log(file.path);
        //如果是数据流
        if(file.isStream()){
            //弹出不支持数据流方式的错误
            this.emit('error',new PluginError(PLUGIN_NAME,'不支持stream'))
        }
        //如果buffer
        if(file.isBuffer()){
             //file.contents默认是buffer格式的数据,需要首先转成字符串
            //添加浏览器
            var res = doReplace(file.contents.toString('utf-8'),config)
           //更改被处理文件的内容
            file.contents = new Buffer(res);
            //输出适配完毕
            gutil.log(gutil.colors.green('适配完毕'))
        }
        this.push(file);
        cb && cb()

    })

    return stream;
};
//增加浏览器前缀
function doReplace(content,config){
    config = config || {
        prefix:['-webkit-','-moz-','-ms-','-o-',''],
        property:['border-image','border-radius','box-shadow','background-origin','background-clip','background-size','box-sizing','box-pack','box-flex','transform','transform-origin','animation','transition','flex','appearance'],
        value:['flex']
    };
    var prefix = config.prefix;
    var regProperty = new RegExp('('+config.property.join('|')+')[^;]+(;|$)','g');
    var regValue = new RegExp('[\\w\\d]+[\\s]?:[\\s]?('+config.property.join('|')+')(;|$)');
    var content = content.replace(regProperty,function(v){
        var str = '';
        var vs = v.replace(';','').split(':');
        for(var i=0;i<prefix.length;i++){
            str+=prefix[i]+vs[0]+':'+vs[1]+';\n';
        }
        return str;
    }).replace(regValue,function(v){
        var str = '';
        var vs = v.replace(';','').split(':');
        vs[1] = vs[1].replace(/\s+/,'')
        for(var i=0;i<prefix.length;i++){
            str+=vs[0]+':'+prefix[i]+vs[1]+';\n';
        }
        return str;
    })

    return content;
}
//导出模块
module.exports = prefix;

这样便编写了增加浏览器前缀的gulp插件,另外增加的浏览器前缀和替换的数据,都是写死在代码里面,可以以参数形式传入

使用gulp-css-prefix

由于没有将这个插件发布到npm,本地使用时,将整个gulp-css-prefix文件夹放到项目的node_modules的文件夹下

var gulp = require('gulp'),
    rename = require('gulp-rename'),
    cssPrefix = require('gulp-css-prefix');

gulp.task('watch',function(){
    gulp.watch(['**/*.css','!**/*.prefix.css'],function(file){
        gulp.src(file.path)
            .pipe(cssPrefix())
            .pipe(rename({suffix:'.prefix'}))
            .pipe(gulp.dest('./dist/'))
    })
})

执行

gulp watch

新建文件index.css

*{
    box-sizing:border-box; 
}

保存

这时便看到在dist目录下生成了,一个index.prefix.css

*{
    -webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
-ms-box-sizing:border-box;
-o-box-sizing:border-box;
box-sizing:border-box;

}

就完成了一个基本的gulp插件

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant