我进行了stackoverflow搜索并查看了Grunt API文档,但无法找到使用grunt.task.run(taskname)运行参数化任务的方法。
我有一个简单的任务,它接受一个参数并在控制台上打印消息:
grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
console.log('hello ' + name + '!');
});
我使用以下任务调用上述任务,该任务验证任务,如果任务存在,则运行它:
grunt.registerTask('validateandruntask', 'if task available then run given task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.warn('task name is needed to run this task');
}
if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskname);
}
});
现在从命令行开始,我正在通过'你好'任务作为参数来验证和运行'但我无法将参数传递给'你好'来自命令行的任务:
这是我在命令行上尝试的但它没有工作:
grunt validateandruntask:hello = foo
grunt validateandruntask:hello:param = name
答案 0 :(得分:2)
首先,通过命令行传递arg的方法是使用:
。
例如,直接致电hello
:
grunt hello:you
要使用多个参数调用它,只需将它们分隔为:
,例如
grunt hello:mister:president
要在任务中使用这些多个参数,您可以使用普通Javascript:使用arguments
(all details here):
grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
// unfortunately arguments is not an array,
// we need to convert it to use array methods like join()
var args = Array.prototype.slice.call(arguments);
var greet = 'hello ' + args.join(' ') + '!';
console.log(greet);
});
然后你想调用grunt validateandruntask:hello:mister:president
,并修改你的代码来处理变量参数:
grunt.registerTask('validateandruntask', 'if task available then run given task', function(taskname) {
if(!taskname || !taskname.length) {
grunt.fail.fatal('task name is needed to run this task');
}
var taskToCall = taskname;
for(var i = 1; i < arguments.length; i++) {
taskToCall += ':' + arguments[i];
}
console.log(taskToCall);
if(!grunt.task.exists(taskname)) {
grunt.log.writeln('this task does not exist!');
} else {
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(taskToCall);
}
});