DEV Community

loading...

How to create a custom task in grunt

konstantinosblatsoukasrepo profile image Konstantinos Blatsoukas ・1 min read

A an example of how you can create a custom task using grunt (in terms of steps)

  • The initial Grunt.json looks like the following
module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json')
  });

};
Enter fullscreen mode Exit fullscreen mode
  • inside the function you add the following line:
  //   My custom task.
  grunt.registerTask('MySuperTask', 
                     'This is a magical task!', 
                     () => console.log('The super custom task is executed...'));
Enter fullscreen mode Exit fullscreen mode
  • the first argument in the name of the task
  • the second argument is the task description
  • the actual code that is going to be executed for that task

So the Grunt.js becomes:

module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json')
  });

    //   My custom task.
  grunt.registerTask('MySuperTask', 
                     'This is a magical task!', 
                     () => console.log('The super custom task is executed...'));

};
Enter fullscreen mode Exit fullscreen mode
  • you run the task by running the following command from your terminal (I assume that the grunt-cli is installed):
  grunt MySuperTask
Enter fullscreen mode Exit fullscreen mode

Bonus: gradle and grunt

You can perform a grunt task through gradle, doing the following:

  • include in the plugins section of the build.gradle file, the plugin:
  id "com.moowork.grunt" version "1.2.0"
Enter fullscreen mode Exit fullscreen mode
  • you can run the custom task by executing the following line:
gradle grunt_MySuperTask
Enter fullscreen mode Exit fullscreen mode

The translated custom task in the gradle is in the form: grunt_CustomTaskNameInGrunt

Cheers!

Discussion (0)

pic
Editor guide