Handling Parameters

Grunt task definitions can take in simple arguments. Let’s demonstrate how this works by creating a simple “greeting” task. As before, we’ll use grunt.registerTask to create a task, but this time we’ll define a parameter in the callback function.

basics/kicking_tires/Gruntfile.js
 
grunt.registerTask(​'greet'​, ​function​(name){
 
grunt.log.writeln(​'Hi there, '​ + name);
 
});

In the body of the callback, we reference the variable just like we would in any plain JavaScript code.

Run this task with

 
$ ​grunt greet

and you’ll see this output:

 
Running "greet" task
 
Hi there, undefined
 
 
Done, without errors.

We didn’t actually pass an argument to the task, and so the ‘name‘ parameter’s value is undefined. Grunt didn’t throw an error message at us.

To supply the parameter, we use a colon followed by the value, like this:

 
$ ​grunt greet:Brian

And now we see what we’re looking for.

 
Running "greet:Brian" (greet) task
 
Hi there, Brian
 
 
Done, without errors.

We don’t have to stop at one argument, though. We can define tasks with multiple arguments. Let’s create another rather silly task that adds some numbers together.

In the Gruntfile, add this task:

basics/kicking_tires/Gruntfile.js
 
grunt.registerTask(​'addNumbers'​, ​function​(first, second){
 
var​ answer = Number(first) + Number(second);
 
grunt.log.writeln(first + ​' + '​ + second + ​' is '​ + answer);
 
});

To run this task, we have to supply both numbers as arguments to the task, and we do that using colons, like this:

 
$ ​grunt addNumbers:1:2

And when we do that, we see this result:

 
Running "addNumbers:1:2" (addNumbers) task
 
1 + 2 is 3
 
 
Done, without errors.

Pretty easy so far, isn’t it? But what if the user didn’t enter appropriate values? We need a way to handle that gracefully.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.105