grunt对象之api

  grunt已经扯了七篇了,殊为不易。最后一篇扯点早应该提及的东西,就是module.exports = function(grunt) {}传入的这个grunt。之前的代码grunt一般只出现在Gruntfile.js这几个地方。

require('load-grunt-tasks')(grunt);
require('time-grunt')(grunt);
grunt.initConfig({
    ...
});
grunt.registerTask('default', [...]);

  但grunt的内容远远不止这些,它包含9个对象属性,而上面的initConfig、registerTask不过是某些属性对象的方法,是为了方便用户调用所取的别名而已。

  9个对象将分别进行介绍。

  1. config
    grunt.config.init(obj): grunt.initConfig()的元神,不必多说了吧。
    grunt.config(prop[, value]): 可以叫语法糖么,当参数为一个的时候调用grunt.config.get()。当参数为两个的时候调用grunt.config.set()。
    grunt.config.get/set(prop[, value]): 设置或者获取prop
    grunt.config.getRaw(prop): 获取prop的原始code
    grunt.config.process(templateString): 返回<%=var.prop%>这种模板对应的值。一般来说,设置的prop当value为string时(比如src,dest)可以直接使用模板,但是当value为function时,想要通过模板获取字符串就需要用到这个方法了。
    举个栗子,自己感受吧。
    'use strict';
    
    module.exports = function(grunt) {
        
        require('load-grunt-tasks')(grunt);
        require('time-grunt')(grunt);
        
        var path = {
            src: 'src',
            dest: 'dest'
        }
        
        grunt.config.init({
            path: path,
            copy: {
                test: {
                    files: [
                        {
                            expand: true,
                            cwd: '<%=path.src%>/',
                            src: '{,*/}*',
                            dest: '<%=path.dest%>'
                        }
                    ]
                }
            }
        });
        
        grunt.config('clean', {
            test: '<%=path.dest%>'
        });
        
        console.log(grunt.config('path').dest);                     //output: dest
        console.log(grunt.config.process('<%=path.dest%>'));        //output: dest
        console.log(grunt.config.get('clean').test);                //output: dest
        console.log(grunt.config.getRaw('clean').test);             //output: <%=path.dest%>
        
        grunt.registerTask('default', ['clean', 'copy']);
    }

     

  2. event
    grunt.event.on(type, listener): 设置某类型事件的监听函数
    grunt.event.once(type, listener): 设置某类型事件的一次性监听函数
    grunt.event.many(type, count, listener): 设置某类型事件的多次性监听函数
    grunt.event.off(type, listener): 取消某类型事件的某个监听函数
    grunt.event.removeAllListeners([type]): 取消某类型事件的全部监听函数
    grunt.event.emit(type[, arg1[, arg2...]]): 发出某类型时间
    需要注意的是,grunt中没有原生的event type,全部自己定义自己发出。
    这部分方法比较简单,和jQuery的命名很相似,所以直接给出代码和输出过了吧。
    'use strict';
    
    module.exports = function(grunt) {
    
        function foron(count) {
            console.log('test for off ' + count);
        }
        
        grunt.event.on('test', foron);
        grunt.event.on('test', function(count) {
            console.log('test for on ' + count);
        });
        
        grunt.event.once('test', function(count) {
            console.log('test for once ' + count);
        });
        
        grunt.event.many('test', 2, function(count) {
            console.log('test for many ' + count);
        });
        
        grunt.event.emit('test', 1);
        grunt.event.emit('test', 2);
        grunt.event.emit('test', 3);
        grunt.event.off('test', foron);
        grunt.event.emit('test', 4);
        grunt.event.removeAllListeners();
        grunt.event.emit('test', 5);
        
        grunt.registerTask('default', []);
    }

    输出如下:

    test for off 1
    test for on 1
    test for once 1
    test for many 1
    test for off 2
    test for on 2
    test for many 2
    test for off 3
    test for on 3
    test for on 4

     

  3. fail
    grunt.fail.warn(msg[, errorcode]): grunt.warn()的本尊,显示一条警告信息然后退出grunt的本次执行,执行grunt时使用--force参数无视警告信息继续执行
    grunt.fail.fatal(msg[, errorcode]): grunt.fatal()的本尊,显示一条错误信息然后退出grunt的本次执行
    Gruntfile.js中一般是用不到的,如果你编写plugin就肯定用的到了。

  4. file 文件操作,封装了nodejs中的fs模块
    grunt.file.defaultEncoding: 文件编码,默认是'utf8'
    grunt.file.preserveBOM: 是否在档首保留BOM,默认false

    grunt.file.read(filepath[, options]): 读取并返回文件内容,options.encoding为null时返回Buffer,其他返回String
    grunt.file.readJSON(filepath[, options]): 读取并返回文件内容的JSON对象表示,常见var pack = grunt.file.readJSON('package.json');
    grunt.file.readYAML(filepath[, options]): 同上,我表示不懂YAML
    grunt.file.write(filepath, contents[, options]): 将contents写入filepath,contents可以是String或Buffer

    grunt.file.copy(srcpath, destpath[, options]): 拷贝文件,会自动创建文件夹
    grunt.file.delete(filepath[, options]): 删除文件

    grunt.file.mkdir(dirpath[, options]): 创建文件夹
    grunt.file.recurse(rootdir, callback): 遍历文件夹下的所有文件(包括子文件夹下的),并执行callback(abspath, rootdir, subdir, filename)

    grunt.file.expand([options, ]patterns): 返回patterns匹配的所有路径,比如我之前的项目结构grunt.file.expand('src/**')返回的如下
    [ 'src',
      'src/css',
      'src/css/base.css',
      'src/css/main.css',
      'src/image',
      'src/image/haiys02.jpg',
      'src/index.html',
      'src/js',
      'src/js/hellogrunt.js',
      'src/js/helloworld.js' ]

    grunt.file.expandMapping(patterns, dest[, options]): 返回patterns匹配路径和原路径的键值对,比如grunt.file.expandMapping('**', 'dest', {cwd: 'src'})返回

    [ { src: [ 'src' ], dest: 'dest' },
      { src: [ 'src/css' ], dest: 'dest/css' },
      { src: [ 'src/css/base.css' ], dest: 'dest/css/base.css' },
      { src: [ 'src/css/main.css' ], dest: 'dest/css/main.css' },
      { src: [ 'src/image' ], dest: 'dest/image' },
      { src: [ 'src/image/haiys02.jpg' ],
        dest: 'dest/image/haiys02.jpg' },
      { src: [ 'src/index.html' ], dest: 'dest/index.html' },
      { src: [ 'src/js' ], dest: 'dest/js' },
      { src: [ 'src/js/hellogrunt.js' ],
        dest: 'dest/js/hellogrunt.js' },
      { src: [ 'src/js/helloworld.js' ],
        dest: 'dest/js/helloworld.js' } ]

    grunt.file.match([options, ]patterns, filepaths): 返回filepaths中匹配patterns的路径
    grunt.file.isMatch([options, ]patterns, filepaths): filepaths中一旦有path命中即返回true

    grunt.file.exists(path1[, path2...]): 返回paths是否存在
    grunt.file.isLink/Dir/File(path1[, path2...]): 返回paths是否为链接、文件夹、文件

    grunt.file.isPathAbsolute(path1[, path2...]): 返回paths是否为绝对路径
    grunt.file.arePathsEquivalent(path1[, path2...]): 返回paths是否相同
    grunt.file.doesPathContain(dir, path1[, path2...]): 返回paths是否在dir中
    grunt.file.isPathCwd(path1[, path2...]): 返回paths是否为cwd
    grunt.file.isPathInCwd(path1[, path2...]): 返回paths是否在cwd中,cwd不在cwd中
    grunt.file.setBase(path1[, path2...]): 设置当前的cwd

  5. log/verbose
    grunt.log.write[ln](msg): 打印 msg
    grunt.log.error[lns](msg): 打印 红色'>>' msg
    grunt.log.ok[lns](msg): 打印 绿色'>>' msg
    grunt.log.subhead(msg): 打印 高亮msg
    grunt.log.writeflags(obj, prefix): 打印 prefix: obj.toString()
    grunt.log.debug(msg): 当指定--debug时打印 [D] msg

  6. option
    grunt.option(key[, value]): 读取或设置option grunt --key1=value1 --key2=value2
    grunt.option.init([obj]): 初始化option对象
    grunt.option.flags(): 将option对象以'key=value'字符串数组方式返回

  7. task
    grunt.task.registerTask(taskname, taskslist)/(taskname, desc, taskFunction): grunt.registerTask的真身,注册可执行的任务
    grunt.task.registerMultiTask(taskname, desc, taskFunction): grunt.registerMultiTask的真身,注册新的task类型,需指定target才能执行,function内部通过this.target获取当前target,通过this.data获取当前target的value
    'use strict';
    
    module.exports = function(grunt) {
        
        require('time-grunt')(grunt);
        
        grunt.initConfig({
          log: {
            foo: [1, 2, 3],
            bar: 'hello world',
            baz: {
                options: {
                    bool: false
                }
            }
          }
        });
    
        grunt.task.registerMultiTask('log', 'Log stuff.', function() {
          grunt.log.writeln(this.target + ': ' + this.data);
        });
        
        grunt.registerTask('default', ['log']);
    }

    输出如下:

    Running "log:foo" (log) task
    foo: 1,2,3
    
    Running "log:bar" (log) task
    bar: hello world
    
    Running "log:baz" (log) task
    baz: [object Object]

    grunt.task.renameTask: 重命名task type,原task type将不可使用
    grunt.task.loadTasks: grunt.loadTasks的真身,指定需要加载的文件的目录
    grunt.task.loadNpmTasks: grunt.loadNpmTasks的真身,指定需要加载的plugin
    以下语句效果相同

    grunt.loadTasks('node_modules/grunt-contrib-clean/tasks/');
    grunt.loadNpmTasks('grunt-contrib-clean');

    grunt.task.run(tasksList): 执行任务队列
    grunt.task.clearQueue(): 清空任务队列
    grunt.task.normalizeMultiTaskFiles(): 将target将要处理的文件以src-dest-orig对象数组的形式序列化,以config中Gruntfile.js为例,添加代码

    console.log(grunt.task.normalizeMultiTaskFiles(grunt.config.process('<%=copy.test%>')));

    打印出的内容如下:

    [ { src: [ 'src/css' ],
        dest: 'dest/css',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/css/base.css' ],
        dest: 'dest/css/base.css',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/css/main.css' ],
        dest: 'dest/css/main.css',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/image' ],
        dest: 'dest/image',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/image/haiys02.jpg' ],
        dest: 'dest/image/haiys02.jpg',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/index.html' ],
        dest: 'dest/index.html',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/js' ],
        dest: 'dest/js',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/js/hellogrunt.js' ],
        dest: 'dest/js/hellogrunt.js',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } },
      { src: [ 'src/js/helloworld.js' ],
        dest: 'dest/js/helloworld.js',
        orig: { expand: true, cwd: 'src/', src: [Object], dest: 'dest' } } ]

     

  8. template
    grunt.template.process(templateString, options): 处理模板字符串,与grunt.config.process相似但不同,返回string,options中的data属性存放context
    grunt.template.date(date, format): 格式化日期,format 'yyyy-mm-dd HH:MM:ss'
    grunt.template.today(format): 格式化今天的日期
  9. util
    grunt.util.kindOf(value): 返回值的类型,比typeof详细
    grunt.util.error(msg[, origError]): 返回一个错误
    grunt.util.linefeed: 当前系统的换行符
    grunt.util.normalizelf(string): 将string中的换行符替换成当前系统的换行符
    grunt.util.recurse(array/object, callback, continueFunction):  递归传入array/object的值,如果continueFunction返回false,则返回原值,continueFunction返回true,则返回callback的值。
    var arr = [1, 2, 3],
            result = grunt.util.recurse(arr, function(value) {
                console.log('value ' + value);
                return value * value;
            }, function(value) {
                if(value % 2 === 0)
                    return false;
            });
        console.log('result ' + result);

    输出:

    value 1
    value 3
    result 1,2,9
    grunt.util.repeat(n, str): 返回重复n次str的值
    grunt.util.pluralize(n, str, separator): 以separator分隔str并返回第n个元素
    grunt.util.spawn(options, doneFunction): 创建子进程执行任务,子进程退出时调用doneFunction
    options{cmd: command, grunt: false, args: arguments, opts: options, fallback: value}
    grunt.util.toArray(obj): 转换为数组
    grunt.util.callbackify: 将一个同步函数转换为异步函数,即将带返回值的函数转换为一个传入回调函数的函数
    function add1(a, b) {
        return a + b;
    }
    function add2(a, b, callback) {
        callback(a + b);
    }
    
    var fn1 = grunt.util.callbackify(add1);
    var fn2 = grunt.util.callbackify(add2);
    
    var result1 = fn1(1, 2, function(result) {
        console.log('1 plus 2 equals ' + result);
    });
    var result2 = fn2(1, 2, function(result) {
        console.log('1 plus 2 equals ' + result);
    });
    
    console.log(result1);
    console.log(result2);

    输出:

    1 plus 2 equals 3
    1 plus 2 equals 3
    undefined
    undefined

 

  好了,这大体就是整个grunt的api介绍了,现在写一个比较完善和优美的Gruntfile.js应该不是什么问题了吧。
  以后有机会可能会补充些编写grunt plugin的内容,现在就告一段落了。

  

转载于:https://www.cnblogs.com/tarol/p/4256475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值