Improve your productivity with grunt JS

grund-js-opt

 

As a web developer, there are many tasks that every and each one of us do in a regular basis and some of these tasks are:

  • Compile coffeescript to javascript
  • Compile Sass or LESS to css
  • Check the quality of your code using one of the famous javascript linters like JsHint or JsLint
  • Minify JS and CSS files for deployment in the production environment
  • Minify your images
  • Run your unit tests

I’m sure I’ve listed almost all the major repetitve tasks done by almost every single web developer and I’m sure also that there are more stuff that you have to repeat depending on the project you’re working on.

The problem here is all of these tasks are simply your JOB, you have to get through them in order to release a great website or web applications and ensure also the quality of your product, so you can’t get rid of them that easily. Now and thanks to Ben Alman, the creator of GruntJS, you can automate all of these repetitive tasks and all the work will be done for you, you only have to learn how to use it.

What’s GruntJS

GruntJs is a task-based command line tool written in Javascript on top of NodeJS. It has a bunch of built-in tasks that will get you started automating your repetitive tasks and because gruntjs was very successful in the community of web developers there is a huge list of gruntJs plugins that will be very useful to you, you can even create your own plugin if you want but let’s keep this to another time.

Installing GruntJS

Installing gruntJs is very easy because it’s available as a node package. First of all, you have to ensure that you have already installed NodeJS then you can install gruntJs by using this command:

npm install -g grunt-cli

this Command Line Interface (CLI) will let you run grunt from any folder because it will add grunt as a command in your system Path

Creating your Grunt project

Like any other nodeJs project, in order to start using gruntjs you need 2 special files

  • package.json: store all the needed informations about your project + list all the plugins needed as devDependencies
  • Gruntfile.js: this is where all the magic stuff will be configured 🙂

You can generate the package.json file automatically by using the command below and provide all the informations (not all are required)

npm init

This init utility will guide you through the process of creating a standard and valid package.json file and after filling all the informations you’ve been asked for you’ll get a json file that looks like this:

{
  "name": "gruntsample",
  "version": "1.0.0",
  "description": "Example of using gruntjs",
  "main": "gruntfile.js",
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "gruntjs"
  ],
  "author": "Naim Hammadi",
  "license": "ISC"
}

Next we have to install grunt and all the plugins we’re going to use as a devDependecies, these resuired packages will be listed in the devDependencies section inside our package.json file
Like we have installed grunt-cli using the NodeJs package manager, we are going to do the same to grunt and the grunt-contrib-concat plugin that will help us concatenate all of our JS files

npm install grunt --save-dev
npm install grunt-contrib-concat --save-dev

This is the final version of our package.json file

{
  "name": "gruntsample",
  "version": "1.0.0",
  "description": "Example of using gruntjs",
  "main": "gruntfile.js",
  "scripts": {
    "test": "grunt"
  },
  "keywords": [
    "gruntjs"
  ],
  "author": "Naim Hammadi",
  "license": "ISC",
  "devDependencies": {
    "grunt": "~0.4.4",
    "grunt-contrib-concat": "~0.4.0"
  }
}

We have installed all the tools we need but we still need the gruntJS entry point that manage all of this: Gruntfile.JS:
This file will hold all the configuration options needded to automate the concatenation of our JS files and it must have all of the following parts:

The Wrapper function

module.exports = function(grunt) {
  // all of your code must be here
};

Tasks configurations

    grunt.initConfig({
        concat: {
            dist: {
                options: {
                    separator: '\n\r',
                    banner: '/*\nThis is a sample JS file \n' +
                            'Author: Naim Hammadi \n' +
                            'Release Date: <%= grunt.template.today("yyyy-mm-dd") %>' +
                            '\n */ \n'
                },
                // the files to concatenate
                src: ['src/basic.js', 'src/main.js'],
                // the location of the resulting JS file
                dest: 'js/all.js'
            }
        }
    });

Loading Grunt plugins and tasks

// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-concat');

Custom tasks

You can configure Grunt to run one or more tasks by default

    // define the default task that can be run just by typing "grunt" on the command line
    // the array should contains the names of the tasks to run
    grunt.registerTask('default', ['concat']);

Now, this is how the whole gruntfile.js should looks like

module.exports = function (grunt) {
    'use strict';
    grunt.initConfig({
        concat: {
            dist: {
                options: {
                    separator: '\n\r',
                    banner: '/*\nThis is a sample JS file \n' +
                            'Author: Naim Hammadi \n' +
                            'Release Date: <%= grunt.template.today("yyyy-mm-dd") %>' +
                            '\n */ \n'
                },
                // the files to concatenate
                src: ['src/basic.js', 'src/main.js'],
                // the location of the resulting JS file
                dest: 'js/all.js'
            }
        }
    });

    // this would be run by typing "grunt test" on the command line
    // the array should contains the names of the tasks to run
    grunt.loadNpmTasks('grunt-contrib-concat');

    // define the default task that can be run just by typing "grunt" on the command line
    // the array should contains the names of the tasks to run
    grunt.registerTask('default', ['concat']);
};

In order to run the configured tasks you need to run the grunt command from your command line console. If all the configuration options are well written, you’ll get a success message and you’ll have the final JS file.

gruntjs

Summary

As you can see, GruntJS is the right tool that every web developer should use to automate his tasks and improve his productivity.
There is too many custom plugins that you can use for every common task and if you don’t find what you’re looking for remember, you can create your own gruntjs plugin.
Don’t forget that GruntJs is an open source project and if you like it, don’t hesitate to contribute to it.
For more informations about gruntJS, please check the official website: http://gruntjs.com/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s