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

相关文章
|
SQL XML Java
Mybatis系列(二)之动态SQL和模糊查询
Mybatis系列(二)之动态SQL和模糊查询
|
运维 监控 安全
分布式系统的演进对企业数字化转型的影响
【10月更文挑战第24天】分布式系统的演进对企业数字化转型产生了深远的影响。它为企业提供了强大的技术支撑,推动了企业在各个方面的发展和进步。然而,企业也需要清醒地认识到分布式系统带来的挑战和风险,积极应对,才能在数字化转型的道路上取得成功。
203 4
|
数据采集 算法 搜索推荐
数据挖掘实战:基于KMeans算法对超市客户进行聚类分群
数据挖掘实战:基于KMeans算法对超市客户进行聚类分群
3119 0
|
并行计算 编译器 C语言
cuda 探索
cuda 探索
133 1
|
人工智能 供应链 5G
|
存储 JavaScript 前端开发
LayUI基本元素之选项卡的使用(详解)
LayUI基本元素之选项卡的使用(详解)
585 0
|
存储 搜索推荐 NoSQL
抖音是怎么做到不重复推荐内容呢?
抖音是怎么做到不重复推荐内容呢?
|
数据采集 运维 供应链
什么是MES?国内做MES系统的企业哪家好?
MES(英文全称:Manufacturing Execution System)制造执行系统,是面向车间生产的管理系统。
|
架构师 Java 关系型数据库
招生CRM系统|基于Springboot实现培训机构招生CRM管理系统
基于前后端分离开发的模式实现一个培训机构的小型CRM管理系统,主要实现根据不同的身份角色来进行不同的管理操作,主要完成的功能有,用户管理、咨询师管理、签到管理、学生跟踪信息管理、学生信息管理等相关功能模块。作者简介:Java领域优质创作者、CSDN博客专家 、掘金特邀作者、多年架构师设计经验、腾讯课堂常驻讲师。主要内容:Java项目、毕业设计、简历模板、学习资料、面试题库、技术互助。数据库:Mysql: mysql5.7+Redis。语言环境:Java: jdk1.8。项目编号:BS-GX-044。
241 0
招生CRM系统|基于Springboot实现培训机构招生CRM管理系统
|
SQL 存储 监控
日志审计服务新功能介绍(全局数据视图及DRDS接入)
阿里云日志服务作为行业领先的日志大数据解决方案,一站式提供数据收集、清洗、分析、可视化和告警功能。日志审计APP提供多账户下跨多云产品审计相关日志进行实时自动化中心化采集,并提供审计需要的存储、查询、信息汇总支持。
2451 0
日志审计服务新功能介绍(全局数据视图及DRDS接入)