Enrolled to Infinite Learning

Wednesday, 24 June 2015

Grunt: Getting Started

These days web application's life cycle is not limited to mere coding, but how the whole execution takes place, the application's performance, code quality, efficient maintenance of large applications and ease of release. To accomplish all this, UI development phase has taken a leap in terms of usage of modern tools. Grunt is one such powerful tool.

Grunt is a task runner that can dramatically improve your front-end development workflow. With the use of a number of grunt plugins you can automate tasks such as compiling LESS, optimizing images and validating your JavaScript code with JSHint.
Grunt deals with frontend automation. The tasks that need to be performed by developers are simplified by using automation. It is similar to Maven that is used for Java development.
Grunt.js is a task-based command line tool written in JavaScript on top of the Node.js platform. Grunt is a task runner that can dramatically improve your front-end development workflow. You can write your most complicated tasks once and leverage them in all of your projects using project specific configuration with the help of grunt.js. 
 
In this blog post you are going to learn how to set up Grunt and configure some recommended tasks.

A few of the most recommended tasks for a web application are –
  1. JS Hint - JSHint is a community-driven tool to detect errors and potential problems in JavaScript code and to enforce your team's coding conventions. It is very flexible so you can easily adjust it to your particular coding guidelines and the environment you expect your code to execute in.  
  2. Concatenation – To enhance performance of your webapp, and speed up the processing concatenation and minification are helpful. A bunch of files concatenated into one at the run time would reduce loading time on the browser. 
  3. Minification – Minification is also required for the same purposes as concatenation. It involves removal of all the unnecessary characters from js code which include white spaces, new line characters, comments etc, which are used to add readability to the code but are not required for it to execute. 
  4.  Optimize images - Optimizing images can often yield some of the largest byte savings and performance improvements for your website: the fewer bytes the browser has to download, the less competition there is for the client's bandwidth and the faster the browser can download and render useful content on the screen. Although optimization can be done at the designer’s end itself,
  5. Preprocessing – This task would output the generated code from a preprocessor like CSS file out of LESS or SASS and js file from .coffee file.
A grunt setup simply comprises of – package.json (lists the grunt and grunt plugins) and Gruntfile (used to define or configure tasks and load grunt plugins). The package.json file involves minimal learning for the developers who are acquainted with JSON.

Installing the Grunt Command Line Interface
Our first job is to install the Grunt command line interface. This is responsible for locating the grunt library in your project and loading the Gruntfile.js configuration.

Grunt and Grunt plugins are both installed using npm, the Node.js package manager. If you don’t have Node.js installed on your machine visit the download page and grab the installer for your operating system. Follow the steps in the installation wizard and you should be up and running in no time. npm is included in the install.

Once you have Node.js and npm installed you can install the grunt-cli package.

npm install -g grunt-cli

Creating a package.json File
Now that you’ve got the Grunt CLI installed it’s time to install the Grunt task runner.

In order to better manage the dependencies for your project it’s best to create a package.json file.

The package.json file should be placed in the root of your project. This file defines data about the project such as the project name, version and author. The package.json file is also responsible for managing dependencies. The devDependencies property defines the different packages that are needed for your application.

{
 "name": "project-name", 
 "version": "0.1.0",
 "author": "Your Name", 
 "devDependencies": {
       "grunt": "~0.4.1", 
       "grunt-contrib-jshint": "~0.6.3", 
       "grunt-contrib-watch": "~0.5.3"      
    }
}

This is a basic example of package.json. To check out all available properties, visit the official documentation.

To install all the dependencies, run the following command-

npm install

This command will fetch all of the packages and store them in a new node_modules directory in your project route.  To install additional packages, you may run the below command, specifying the name of the package you wish to install.

npm install <module> --save-dev

Using the --save-dev flag will cause npm to automatically add this package to the dependencies in your package.json file.

Defining Tasks in the Gruntfile
Once you are done with package.json and npm installation, it's time to add tasks to your grunt file.
Create a file called Gruntfile.js. This is where you define and configure the tasks that you want Grunt to run.

Lets take a look at an example that uses the plugins specified in your package.json file.

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    watch: {
      css: {
        files: [
          '**/*.css',
          '**/*.less'
        ]
      },
      js: {
        files: [
          'assets/js/*.js',
          'Gruntfile.js'
        ],
        tasks: ['jshint']
      }
    },
    jshint: {
      options: {
        jshintrc: '.jshintrc'
      },
      all: ['Gruntfile.js', 'assets/js/*.js']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');

  // Register the default tasks.
  grunt.registerTask('default', ['watch']);
};
 

You may go over the list of available plugins to look for more plugins.

LOADING THE PLUGINS
 
The next section in the Gruntfile is used for loading each of the plugins you wish to use. These need to be specified in your package.json file and installed using npm install. If you try to run grunt without installing a plugin it will just display an error.

// Load the Grunt plugins.
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');

REGISTERING THE DEFAULT TASKS 
The grunt.registerTask method is used specify a default set of tasks that should run when the grunt command is executed.

// Register the default tasks. 
grunt.registerTask('default', ['watch']);

The first parameter of this method specifies the name of the task (in this case ‘default’) and the second contains an array of the tasks you wish to be executed. The watch task we defined earlier takes care of calling the jshint task, so we only need to specify watch here.

Running Grunt 
Now you are done all the above steps, its time to run your grunt tasks and see how it automates your UI workflow.

Executing the grunt command in your terminal will run all of the tasks specified in your default task. You can also run tasks individually by passing the task name to the grunt command.

grunt // Runs default tasks 
grunt jshint// Just runs the compass task

Verdict 
Grunt is a good place to start automating your UI workflow. There are several other tools like Gulp, but the former wins due to its extensive usage,large community support, wide range of plugins and speed.
Do have a look at what Addy Osmani has to share on Modern UI Workflow here.

0 comments:

Post a Comment

Please share your views here

Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to to, let us concentrate rather on explaining to human beings what we want a computer to do.
--Donald Knuth

Categories

Agile (1) Angular JS (2) CSS (1) css reset (1) Grunt (1) Jasmine (1) Karma (1) Scrum (1) setup (1) Sprint (1) test cases (1) Typescript (1) UI Automation (1) Webstorm (1)
Disclaimer

The information and images of this blog are sometimes referred from various websites and blogs across the web to provide the best possible content to the reader. The information furnished hereby cannot be used for legal purposes. I will not be liable to you (whether under the law of contact, the law of torts or otherwise) in relation to the contents of, or use of, or otherwise in connection with, this website.