Web development blog for Html, CSS, javascript, JQuery developers. At Kodecrash you will find best solution for complex problems.

Creating a simple grunt task

Posted in Javascript

Grunt is a JavaScript task runner used to automate the common tasks such as JS/CSS file minimization, concatenation of multiple JS/CSS files, Sass compilation, JS linting, code formatting etc.

To get started with grunt you need to install node JS latest version from node JS website.

https://nodejs.org/

Create Node project

From node.js command prompt, go to the project directory.
grunt-1

Type: “npm init”, then: “enter”
grunt-2
follow steps, enter only a name for the site, no need to change other default values. “npm init” command creates a package.json file. Refer the screenshot below.
grunt-3

Install grunt
Use the npm command below to install grunt specific to your project.
grunt-4
–save-dev command adds the dev dependency in the package.json file.
package.json file will look like this.
grunt-5

Create Gruntfile.js in the project root directory. We will use this file to create and configure grunt tasks. Add the below code in the Gruntfile.js.
grunt-12

It’s time to create a grunt task. Create a simple grunt task named logTask using grunt.registerTask function.

  grunt.registerTask('logTask', function() {
    console.log('Inside Log Task');
  });

Your gruntfile will look like this.
grunt-6

Now call the logTask using the command below. “Inside Log Task” text will get printed in the console.

     grunt  logTask

grunt-7

You can create multiple grunt task in the same Gruntfile.
grunt-8

To call the formatTask use the command below.

    grunt formatTask

grunt-9

You can run the above tasks simultaneously by calling both task into the new task.
grunt-10

grunt-11