不知道官网的同学,请访问这个链接:http://www.gruntjs.net/docs/creating-plugins/
按照官网说的,就噼里啪啦的,敲了一大堆东西,大概流程如下:
1、npm安装grunt插件模板
npm install -g grunt-init
这里比较坑,我原本以为,只要npm命令后,模板神马的,就安装好了,结果还有下一步
2、安装grunt插件模板
git clone git://github.com/gruntjs/grunt-init-gruntplugin.git ~/.grunt-init/gruntplugin
这里我就比较任性,没有安装git了,于是,就看了一下grunt-init的源码,发现,其实它是读取grunt-init包下的templates文件夹。
grunt-init到底安装在什么位置?
请输入 npm config get prefix查看,在相应的node_modules目录下,你会发现有一个grunt-init的文件夹,里面就有一个templates的文件夹
我们在这个网址: https://github.com/gruntjs/grunt-init-gruntplugin
把插件下载到本地,然后到templates文件夹下,建一个gruntplugin的文件夹,把上面下载的玩意,解压到里面,就完成模板安装了。
3、把模板安装到一个空目录下
进入一个空的目录,执行命令
grunt-init gruntplugin
命令行会要求你输入一些信息,输入完成后,就会在当前目录生成模板。
4、执行 npm install 安装包的依赖
插件编写:
a) 进入tasks目录,里面就只有一个脚本,在里面编写我们自己的内容
内容大概是这样子的,就在注释里解析一下就算了。
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
// 注册一个多任务,任务名字叫"ttt",后面再将怎么调用
grunt.registerMultiTask('ttt', 'The best Grunt plugin ever.', function() {
// Merge task-specific and/or target-specific options with these defaults.【任务的默认参数哈~,如果外部不传入,就使用当前的值】
var options = this.options({
punctuation: '.',
separator: ', '
});
// 其中,this.files就是当前要处理的文件列表,this.target就是目标文件,this.data就是当前的配置
// 下面就是一个很普通的遍历,map和join操作,不太高深
this.files.forEach(function(f) {
// f含有3个值{dest: 目标文件, src:[要操作的文件], org: {一半用不到~}}
var src = f.src.filter(function(filepath) {
// 检测文件是否存在,不存在,则在列表中移除
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// 因为src已经转为字符串了,所以下面可以对它为所欲为
src += options.punctuation;
// 最后往f.dest中,写入内容[src]
grunt.file.write(f.dest, src);
// 打印信息
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
内容看着就非常高大上,反正我是看了10来分钟,才终于全理解了【表示它的介绍,真心隐秘】。
b) 在Gruntfile.js中使用
grunt.initConfig({
ttt: {
custom_options: {
options: {
separator: ': ',
punctuation: ' !!!'
},
files: {
'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123']
}
}
}
});
grunt.loadTasks('tasks'); // 插件放置的目录哦~,外部引用的时候,自己变通哈
运行一下 grunt ttt看看效果吧~
OK,通过了一系列的官网教程,终于完成了一次艰苦的插件开发之旅。
最后的最后:
好吧,原来插件,就是一个multi任务~~~,突然觉得好废.....【看了那么久教程,到底为了神马啊.......】为什么自己木有更早的洞察呢....
grunt.registerMulitTask("log", "定义了一个log的任务", function(){
this.target; // 目标文件
this.data; // 当前的参数
this.files; // 当前要处理的文件信息
this.options; // fn,合并默认参数,如果木有新的,去传入的参数
// EG:
var options = this.options({
red: true // 默认红色是true,如果initConfig是,设置了red:false,那最后返回外层的是red:false
});
});
反思一下,也不是一无是处,官网的教程,是写公用插件的,而mulitTask是我们平时写小型任务的。
按照官网的规范,可以通过 npm publish 发布,而mulitTask的,只能自己玩了。