grunt-docs
grunt-docs copied to clipboard
Run parametrized task using grunt.task.run(taskname)
I looked at Grunt API docs but couldn't find a way to run a parametrized task using grunt.task.run(taskname). In this case, the taskname parameter may have n number of arguements.
I have a simple task which accepts a parameter and prints the message on console:
grunt.registerTask('hello', 'greeting task', function(name) {
if(!name || !name.length)
grunt.warn('you need to provide a name');
console.log('hello ' + name + '!');
});
I call the above task using below task which validates the task and if task exists then it runs it:
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);
}
});
Now from command line, I am passing 'hello' task as parameter to 'validateandruntask' but I am not been able to pass the parameter to 'hello' task from command line:
This is what I tried on command line but it didn't work:
grunt validateandruntask:hello=foo
grunt validateandruntask:hello:param=name
Is this supported as part of grunt.task.run API or does application need to take care of this by passing additional parameter for child tasks to parent task (in this case, validateandruntask) which will run parametrized tasks?
To put parameters into task.run, use the :
notation, e.g. grunt.task.run("hello:world");
A simple way I found to implement it is to access the arguments
variable within your task.
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 {
// appends parameters onto task
var task = taskname;
for (var i = 1; i < arguments.length; i++) {
task = task + ":" + arguments[i];
}
grunt.log.writeln(taskname + ' exists. Going to run this task');
grunt.task.run(task);
}
});
Thus to pass in the parameters, you could do
grunt validateandruntask:hello:foo;
or
grunt validateandruntask:hello:name;
Contrary to the introduction, the example above does not use any grunt.task.run
with parameters, @victorzchan. And I doubt it works this way.
I thought you could pass arguments onto tasks via grunt.task.run()
, and the task would have access to those arguments. But when I do it, it seems like foo:bar
tries to run subtask bar
inside task foo
... something like dist
inside watch
.
That would mean you can't use :
to pass variables onto tasks.