Getting Started with Grunt Task Runner

Datetime:2016-08-23 02:45:05          Topic: Grunt           Share

About Task Runner

There are certain tasks which front-end developers are often asked to do. Tasks like:

  • CSS file compression
  • JS minification or obfuscation
  • HTML/JSON file minification
  • Image optimisation
  • Compile SASS or LESS files to generate CSS files
  • Unit testing
  • SVN commit
  • Build deployment etc

To do the above tasks we need so many different reliable tools and it is a tedious task to find such types of reliable tools online. And I don’t think any such tool is available which can do all the above tasks in one click.

What if these tasks can be automated and can be done in one key press? To do this, we would need to write few tasks in JS file and run Grunt.

So, what is Task Runner? We can say task runner is in one word Automation. Task runners help us to automate these tasks and perform these tasks synchronously or asynchronously.

Grunt

Grunt is a JavaScript Task Runner and this is a command line tool which runs on NodeJS . It helps us to do all the above tasks very easily with a minimum effort. Grunt ecosystem and its huge list of plugins help us get all front-end code production ready.

Prerequisites

Grunt and Grunt plugins are installed and managed by NodeJS Package Manager (npm). To run grunt commands, it is required to have NodeJS installed in your system.

To test if node and npm are installed in your system, followthe  below steps:

  • Open terminal
  • Type “ node –v ” in command line and press enter. It should show node version.
  • Type “ npm ” in command line and press enter. It should show npm details.

Install Command Line Interface (CLI)

To work with Grunt, it is required to install Grunt’s Command Line Interface (CLI). To install run below command in command line (or terminal in Mac).

npm install -g grunt-cli

This will put the grunt command in your system path, allowing it to be run from any directory.

In Mac it may be required to use sudo to run npm commands. So, in that case, command should look like:

sudo npm install -g grunt-cli

Start with a new Grunt Project

Each grunt project requires two files in your project folder:

  • package.json
  • Gruntfile.js

Create package.json

As mentioned in official website of Grunt , this file is used by npm to store metadata for projects published as npm modules. You will list grunt and the Grunt plugins your project needs as devDependencies in this file. To create package.json:

  1. Change to Project’s root directory in the command line.
  2. Run below command in command line: npm init

This command will askfor a  few inputs. It is not necessary to enter values for any option. Remember to type “Gruntfile.js” when it asks “entry point”. Then continue pressing enter. It will create a package.json file in your project directory. package.json should look like:

{
  “name”: “sampleproject”,
  “version”: “1.0.0”,
  “description”: “”,
  “main”: “Gruntfile.js”,
  “scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″
  },
  “author”: “”,
  “license”: “ISC”
}

Create Gruntfile.js

Gruntfile.js is a JavaScript file which will be used to configure or define tasks and load Grunt plugins. So, to create a Gruntfile.js:

  1. Create a new JavaScript file with name Gruntfile.js in your project directory.
  2. Copy below code to Gruntfile.js and save:
    module.exports = function(grunt) {
    
      grunt.initConfig({
        pkg: grunt.file.readJSON(‘package.json’),
      });
      grunt.registerTask(‘default’, []);
    };
    

Install Grunt

To install grunt in your project folder, run the below command in command line:

npm install grunt –save-dev

Appending –save-dev in any npm command, it adds installed plugin in devDependencies object of the package.json.

package.json should look like:

{
  “name”: “sampleproject”,
  “version”: “1.0.0”,
  “description”: “”,
  “main”: “Gruntfile.js”,
  “scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″
  },
  “author”: “”,
  “license”: “ISC”,
  “devDependencies”: {
    “grunt”: “^0.4.5”
  }
}

Run Grunt command

In command line, type grunt and press enter. Below message should appear in your command line:

Done, without errors.

If above message is appearing in the command line, it means your grunt project is ready and we are good to move forward to add plugins for automation tasks in our Grunt file.

How to Add Tasks in Grunt file

Let’s start with how tasks work by adding a “ test ” task in our Gruntfile.js. Add below code in your Gruntfile.js:

grunt.registerTask(‘test’, ‘My “test” task description.’, function() {
   grunt.log.writeln(‘Currently running the “test” task.’);
});

After adding above task in Gruntfile.js, it should look like:

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON(‘package.json’),
  });

  grunt.registerTask(‘test’, ‘My “test” task description.’, function() {
    grunt.log.writeln(‘Currently running the “test” task.’);
  });

  grunt.registerTask(‘default’, []);
};

Now type “ grunt test ” in your command line and below message should appear in your command line:

Let’s start with a real project. Here we will be discussing a few common tasks which we need while working in a front-end project. These tasks are:

  • HTML file minification
  • JavaScript file minification
  • CSS file compression
  • A task to create final build

I have created a sample project with the below folder structure:

Root folder contains app, dist, node_modules, Gruntfile.js and package.json:

  • App folder is used as the development folder.
  • Dist will be used as the distribution folder where all optimized folder will be stored. Initially its blank.
  • Node_modules, Gruntfile.js and package.json are required to run Grunt command.

Now, let’s add tasks to Gruntfile.js

Remove all contents of “dist” folder

  1. Run below command in command line:

    npm install grunt-contrib-clean –save-dev

  2. Add below code in Gruntfile.js:
    grunt.registerTask(‘removeAllContents’, ‘Removes all files/folders of “dist” folder’, function(){
        grunt.config(‘clean’, {
            contents: [‘dist/*’]
        });
        grunt.task.run(‘clean’);
      });
    
      grunt.loadNpmTasks(‘grunt-contrib-clean’);
    
  3. Run below command in command line:

    grunt removeAllContents

This will remove all contents of the “ dist ” folder.

Copy all folders from “app” to “dist”

  1. Run below command in command line:

    npm install grunt-contrib-copy –save-dev

  2. Add below code in Gruntfile.js:
    grunt.registerTask(‘createFolderStructure’, “Copies all subdirectories to dist folder”, function(){
        grunt.config(‘copy’, {
            main: {
                expand: true,
                cwd: ‘app’,
                src: ‘**’,
                dest: ‘dist/’,
                filter: ‘isDirectory’
            }
        });
        grunt.task.run(‘copy’);
      });
    
    grunt.loadNpmTasks(‘grunt-contrib-copy);
    
  3. Run below command in command line:

    grunt createFolderStructure

    This command should copy css and js folders to “dist” folder without copying its inner finesl. We don’t need inner files as we need minified version of css and js files.

Minify CSS file

  1. Run below command in command line:

    npm install grunt-contrib-cssmin–save-dev

  2. Add below code in Gruntfile.js:
    grunt.registerTask(‘minifyCSSFiles’, “Minifies all CSS files”, function(){
          grunt.config(‘cssmin’, {
            target: {
              files:{
                ‘dist/css/style.min.css’: [‘app/css/style.css’]
              }
            }
          });
          grunt.task.run(‘cssmin’);
      });
    
      grunt.loadNpmTasks(‘grunt-contrib-cssmin’);
    
  3. Run below command in command line:

    grunt minifyCSSFiles

    This command should create a new minified CSS file named style.min.css in dist/css folder. For more on CSS Minification using Grunt, please visit official site .

Minify JavaScript file

  1. Run below command in command line:

    npm install grunt-contrib-uglify–save-dev

  2. Add below code in Gruntfile.js:”
    1. grunt.registerTask( ‘minifyJSFiles’“Minifies all JS files” , function(){
    2.       grunt.initConfig({
    3.         uglify: {
    4.           my_target: {
    5.             files: {
    6.                ‘dist/js/main.min.js’ : [ ‘app/js/main.js’ ]
    7.             }
    8.           }
    9.         }
    10.       });
    11.       grunt.task.run( ‘uglify’ );
    12.   });
  3. Run below command in command line:

    grunt minifyJSFiles

    This command should create a new minified JS file named main.min.js in dist/js folder. For more on JS minification, please visit the official site .

Prepare index.html file

  1. Run below command in command line:

    npm install grunt-htmlcompressor–save-dev

  2. Add below code in Gruntfile.js:
    1. grunt.registerTask( ‘minifyHTMLFiles’“Minifies all JS files” , function(){
    2.     var strData = grunt.file.read( ‘app/index.html’ , {encoding:  ‘utf8’ });
    3.     objReg = /css\/style.css/gi;
    4.     strData = strData.replace(objReg,  ‘css/style.min.css’ );
    5.     objReg = /js\/main.js/gi;
    6.     strData = strData.replace(objReg,  ‘js/main.min.js’ );
    7.     grunt.file.write( ‘dist/index.html’  , strData );
    8.     grunt.initConfig({
    9.       htmlcompressor: {
    10.         compile: {
    11.           files: {
    12.              ‘dist/index.html’‘dist/index.html’
    13.           },
    14.           options: {
    15.             type:  ‘html’ ,
    16.             preserveServerScript:  true
    17.           }
    18.         }
    19.       }
    20.     });
    21.     grunt.task.run( ‘htmlcompressor’ );
    22.   });
    23. grunt.loadNpmTasks( ‘grunt-htmlcompressor’ );
  3. Run below command in command line:

    grunt minifyHTMLFiles

    This command should:

      • Replace main.js to main.min.js in the script tag of index.html.
      • Replace style.css to style.min.css in the style tag of index.html.
      • minify and create index.html in “

    dist

      ” folder.

For more on “HTML minification” please visit the official site .

How to run all commands at once

To run all the tasks on one enter, we need to arrange them sequentially. Update the code in Gruntfile.js as shown below:

grunt.registerTask(‘default’, [‘removeAllContents’,
“createFolderStructure”,
‘minifyCSSFiles’,
‘minifyJSFiles’,
‘minifyHTMLFiles’]);

Now run below command in command line:

grunt

This command will run all the commands sequentially and perform all the tasks to prepare your build.

To know more Grunt plugins please visit official site of Grunt plugins .





About List