grunt实用总结

文章梗概如下:

  1. 如何让Grunt在项目跑起来
  2. 初识:Gruntfile.js
  3. 术语扫盲:task & target
  4. 如何运行任务
  5. 任务配置
  6. 自定义任务
  7. 文件通配符:glob模式
  8. 文件通配符:例子
  9. 常用API
  10. 如何初始化Gruntfile.js
  11. 通过模板初始化Gruntfile.js
  12. 获取命令行参数
  13. 插件编写

入门简介:http://www.cnblogs.com/chyingp/p/what-is-grunt.html

如何让Grunt在项目跑起来

搞定下面三点,就可以愉快地使用grunt了。

  • 安装grunt-cli:globally,命令行工具,所有项目共用
  • 安装grunt:locally,每个项目单独安装
  • 项目根目录下配置文件:Gruntfile.js

初识:Gruntfile.js

module.exports = function(grunt) {
  // 任务配置
  grunt.initConfig({
    concat: {   // concat任务
        foo: {  // 一个任务可以包含多个子任务(官方术语叫做targetsample)
            src: ['a.js', 'b.js'],
            dest: 'ab.js'
        }
    }
  });

  // 配置任务
  grunt.loadNpmTasks('grunt-contrib-concat');
};

剩下的事情:

grunt concat

术语扫盲:task & target

task就是任务,target就是子任务。一个任务可以包含多个子任务。如下所示

 grunt.initConfig({
    concat: {   // task
        foo: {  // target
            src: ['a.js', 'b.js'],
            dest: 'ab.js'
        },
        foo2: {
            src: ['c.js', 'd.js'],
            dest: 'cd.js'
        }
    }
  });

如何运行任务

首先需要配置任务,比如压缩文件

grunt.initConfig({
    uglify: {
        src: 'main.js'
    }
});

然后运行任务

grunt uglify

任务配置

grunt里绝大多数都是文件操作,所以任务配置这一块会重点讲。简单举个例子,我们要将a.jsb.js合并成ab.js,该怎么做呢。

有四种配置方式

  1. Compact Formate
  2. Files Object(不推荐)
  3. Files Array
  4. Older Formats(不推荐,已废弃)

Compact Formate

特点:

  1. 每个target只支持一个src-dest
  2. 支持除了srcdest之外的参数
    concat: {
     foo: {
         src: ['a.js', 'b.js'],
         dest: 'ab.js'
     }
    }
    

File Object

特点:

  1. 每个target支持多个src-dest
  2. 不支持除了srcdest之外的参数
    concat: {
     foo: {
         files: {
             'ab.js': ['a.js', 'b.js']
         }
     }
    }
    

File Array

特点:

  1. 每个target支持多个src-dest
  2. 支持除了srcdest之外的参数
    concat: {
     foo: {
         files: [{
             src: ['a.js', 'b.js'],
             dest: 'ab.js'
         }]
     }
    }
    

中级配置

下面配置的意思:将src目录下的所有swf文件拷贝到dest目录下,并且与原来的目录结构保持一致。

例子:src/flash/upload.swf - dest/upload.swf

copy: {
    dist:{
        files: [{
            expand:true, // 设置为true,表示要支持cwd等更多配置
            cwd: 'src/flash', // 所有的源文件路径,都是相对于cwd
            src:'**/*.swf', // 表示sr/flashc目录下的所有swf文件,这里用了通配符
            dest: 'dist'  // 目标路径

        }]
    },

自定义任务

如果现有插件不能满足你的需求,自己写一个插件又太麻烦,可以考虑自定义任务

// 自定义任务
grunt.registerTask('hello', function(name){
    console.log('hello  ' + name);
});

然后,运行任务

grunt hello:casper

输出:

hello casper

文件通配符:glob模式

  1. * 匹配任意多个字符,除了/
  2. ? 匹配除了/之外的单个字符
  3. ** 匹配任意多个字符,包括/
  4. {} 匹配用逗号分割的or列表
  5. ! 用在模式的开通,表示取反
// You can specify single files:
{src: 'foo/this.js', dest: ...}
// Or arrays of files:
{src: ['foo/this.js', 'foo/that.js', 'foo/the-other.js'], dest: ...}
// Or you can generalize with a glob pattern:
{src: 'foo/th*.js', dest: ...}

// This single node-glob pattern:
{src: 'foo/{a,b}*.js', dest: ...}
// Could also be written like this:
{src: ['foo/a*.js', 'foo/b*.js'], dest: ...}

// All .js files, in foo/, in alpha order:
{src: ['foo/*.js'], dest: ...}
// Here, bar.js is first, followed by the remaining files, in alpha order:
{src: ['foo/bar.js', 'foo/*.js'], dest: ...}

// All files except for bar.js, in alpha order:
{src: ['foo/*.js', '!foo/bar.js'], dest: ...}
// All files in alpha order, but with bar.js at the end.
{src: ['foo/*.js', '!foo/bar.js', 'foo/bar.js'], dest: ...}

// Templates may be used in filepaths or glob patterns:
{src: ['src/<%= basename %>.js'], dest: 'build/<%= basename %>.min.js'}
// But they may also reference file lists defined elsewhere in the config:
{src: ['foo/*.js', '<%= jshint.all.src %>'], dest: ...}

常用API

常用API:文件

文件操作

grunt.file.read(filepath [, options])   // 读文件
grunt.file.readJSON(filepath [, options])   // 读文件:json
grunt.file.write(filepath, contents [, options])    // 写文件
grunt.file.copy(srcpath, destpath [, options])  // 拷贝文件
grunt.file.delete(filepath [, options]) // 删除文件

目录操作

grunt.file.mkdir(dirpath [, mode])  // 创建
grunt.file.recurse(rootdir, callback)   // 遍历

文件类型

grunt.file.exists(path1 [, path2 [, ...]])  // 指定的路径是否存在
grunt.file.isDir(path1 [, path2 [, ...]])   // 指定的路径是否目录
grunt.file.isFile(path1 [, path2 [, ...]])  // 指定的路径是否文件

路径

grunt.file.isPathAbsolute(path1 [, path2 [, ...]])  // 是否绝对路径
grunt.file.arePathsEquivalent(path1 [, path2 [, ...]])  // 是否等价路径
grunt.file.doesPathContain(ancestorPath, descendantPath1 [, descendantPath2 [, ...]]) // 后面的路径是否都是ancestorPath的子路径

API:日志

grunt.log.write(msg)
grunt.log.writeln(msg)

grunt.log.error([msg])  // 打印日志,并中断执行
grunt.log.errorlns(msg)

grunt.log.debug(msg)    // 只有加了--debug参数才会打印日志

API:任务

主要有以下几个

grunt.task.loadNpmTasks(pluginName) // 加载grunt插件

grunt.task.registerTask(taskName, description, taskFunction)    // 注册任务 || 给一系列任务指定快捷方式

grunt.task.run(taskList)    // 代码内部运行任务

grunt.task.loadTasks(tasksPath) // 加载外部任

grunt.task.registerMultiTask(taskName, description, taskFunction)   // 注册插件

定义任务

// 自定义任务
grunt.registerTask('hello', function(name){
    console.log('hello  ' + name);
});

指定别名

指定默认task(运行grunt任务时,如没有指定任务名,默认运行grunt default)

grunt.registerTask('default', ['concat']);

给一系列的任务指定别名

grunt.registerTask('dist', ['clean', 'concat', 'uglify']);

初始化Gruntfile.js

  1. 简单拷贝:简单粗暴有效
  2. 通过模板初始化:(推荐)

通过模板初始化Gruntfile.js

首先,你本地要确保安装了grunt-init,然后将 Gruntfile.js模板 下载到指定目录。具体目录参考这里。然后就很简单了

grunt-init gruntfile

回答几个简单问题

Please answer the following:
[?] Is the DOM involved in ANY way? (Y/n) n
[?] Will files be concatenated or minified? (Y/n) y
[?] Will you have a package.json file? (Y/n) y
[?] Do you need to make any changes to the above before continuing? (y/N) n

Gruntfile.js生成了!

-rw-r--r--  1 root  staff   2.0K  6 20 00:52 Gruntfile.js
-rw-r--r--  1 root  staff   287B  6 20 00:52 package.json

常用tips

获取命令行参数

比如运行了如下命令,怎么获取jshint参数的值呢

grunt dist --jshint=true

很简单

grunt.option('jshint');

 

插件编写

@todo

posted @ 2014-06-23 13:19  程序猿小卡  阅读(3635)  评论(2编辑  收藏  举报