Running Custom Tasks With Grunt

Run custom tasks with Grunt in this lesson!

You need a package.json and Gruntfile.js to run tasks with Grunt.

The package.json

This file has a list of all the required dependencies, including Grunt.

The Gruntfile

The Gruntfile is where you’ll write some actual code to run tasks. It can:

  • Configure tasks.
  • Load plugins. Plugins are used to run ‘prebuilt’ Grunt tasks. Check out our plugins lesson to learn more about these.
  • Register which tasks need to be run.

Running custom tasks

To run a custom task with Grunt, you need:

  1. A JavaScript function that does the task
  2. A name to identify the task

Let’s take a simple example. Suppose you just want to print the phrase, “a simple task.” The supplied JavaScript function would look like:

function(){
  console.log("a simple task");
}

Whereas the identification name can be anything we want. Let’s say we choose to name it ‘simple.’

grunt.registerTask()

To actually run these, you’d supply both of these items to the function grunt.registerTask() in the Gruntfile, like so:

grunt.registerTask('simple', function(){
  console.log("a simple task");
});

Finally, you’d wrap these in the wrapper function module.exports = function(grunt){} and put them in the Gruntfile.

Run the following example and enter grunt simple to see our task run:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.