Our First Task

Let’s kick the tires. We’ll create the default task, which is the one that runs when we type the grunt command.

Every Gruntfile starts out with some boilerplate code. Create a new file called Gruntfile.js and add this:

basics/kicking_tires/Gruntfile.js
 
module.exports = ​function​(grunt){
 
// Your tasks go here
 
}

If you’re familiar with Node.js and its module system, you’ll understand what’s going on here. If you’re not, it’s not a huge deal; just know that this is what Grunt needs to interpret your tasks. You’re defining a Node.js module that receives a grunt object. You’ll use that object and its methods throughout your configuration files. The tasks you define and configure are then made available to Grunt so that they can be executed.

Now, within the curly braces, define the following task, which prints some text to the screen:

basics/kicking_tires/Gruntfile.js
 
grunt.registerTask(​'default'​, ​function​(){
 
console.log(​'Hello from Grunt.'​);
 
});

We use grunt.registerTask to create a new Grunt task. We pass in a task name followed by an associated callback function. Whatever we put in the callback function is executed when we invoke the task.

To see it in action, run this new task from the Terminal:

 
$ ​grunt

You’ll see the following output:

 
Running "default" task
 
Hello from Grunt.
 
 
Done, without errors.

In this task we’ve used Node’s console.log function, but we really should use Grunt’s grunt.log object instead. It’ll give us some flexibility because it supports error logging, warnings, and other handy features.

So, change the following:

basics/kicking_tires/Gruntfile.js
 
console.log(​'Hello from Grunt.'​);

to

basics/kicking_tires/Gruntfile.js
 
grunt.log.writeln(​'Hello from Grunt.'​);

and rerun the task with

 
$ ​grunt

You shouldn’t see anything different. This task is not fancy by any means, but it illustrates that Grunt works, and that we can create a simple task. Let’s move on.

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

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