Tuesday, 21 April 2015

Grunt

What is grunt ?

 Grunt is a task-based command line build tool for JavaScript projects. Here's the idea: when working on a JavaScript project, there are a bunch of things you'll want to do regularly.

To check more details you can go through: http://gruntjs.com/
Getting started: http://gruntjs.com/getting-started


To install grunt just run the command sudo npm install -g grunt
Assuming you have nodejs and npm is installed.

for Grunt's command line interface, you need to install grunt-cli
npm install -g grunt-cli

This will put the grunt command in your system path, allowing it to be run from any directory.
Note that installing grunt-cli does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a Gruntfile. This allows multiple versions of Grunt to be installed on the same machine simultaneously.

Preparing a new Grunt project

A typical setup will involve adding two files to your project: package.json and the Gruntfile.
package.json: 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.
Gruntfile: This file is named Gruntfile.js or Gruntfile.coffee and is used to configure or define tasks and load Grunt plugins. When this documentation mentions a Gruntfile it is talking about a file, which is either a Gruntfile.js or a Gruntfile.coffee.

package.json
To create package.json file you just need to run the command npm init
This will prompt you with some questions (https://docs.npmjs.com/cli/init) provide the details and that's it.

As I specified that this file will contain development dependency of grunt and gruntPlugins, to install grunt plugin and also register it in package.json

npm install <module> --save-dev

For Example: npm install jquery --save-dev

npm install grunt --save-dev
npm install grunt-contrib-jshint --save-dev
npm install grunt-contrib-sass --save-dev
npm install grunt-contrib-watch --save-dev
 
This will install jquery inside node_modules  folder and will add dependecy in package.json


The Gruntfile

The Gruntfile.js or Gruntfile.coffee file is a valid JavaScript or CoffeeScript file that belongs in the root directory of your project, next to the package.json file, and should be committed with your project source.
A Gruntfile is comprised of the following parts:
  • The "wrapper" function
  • Project and task configuration
  • Loading Grunt plugins and tasks
  • Custom tasks

An example Gruntfile

In the following Gruntfile, project metadata is imported into the Grunt config from the project's package.json file and the grunt-contrib-uglify plugin's uglify task is configured to minify a source file and generate a banner comment dynamically using that metadata. When grunt is run on the command line, the uglify task will be run by default.
Say for example I am having all my static files(js, css inside staitc -> src directory)

module.exports = function(grunt) {

    grunt.initConfig({
        jshint: {
            src: ['static/src/**/*.js', 'static/test/**/*.js'],
            options: {
                sub: true, //[] instead of .
                evil: true, //eval
                laxbreak: true, //unsafe line breaks
            },
        },
        sass: {
            dev: {
                options: {
                    style: "expanded",
                },
                files: {
                    "static/src/css/base.css": "static/src/css/base.sass",
                }
            }
        },
        watch: {
            sass: {
                files: ["static/src/css/base.sass"],
                tasks: ['sass']
            },
        }
    });

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

    grunt.registerTask('gen', ["sass"]);
    grunt.registerTask('watcher', ["gen", "watch"]);
    grunt.registerTask('test', []);

    grunt.registerTask('default', ['jshint']);

};

The wrapper function

module.exports = function(grunt) {
  // Do grunt-related things in here
};

 
Every Gruntfile (and gruntplugin) uses this basic format, and all of your Grunt code must be specified inside above function.

Project and Task Configuration

Most Grunt tasks rely on configuration data defined in an object passed to the grunt.initConfig method.
In this example, we uses jshint plugin of grunt and providing paths of JS files

Loading Grunt plugins and tasks

Many commonly used tasks like concatenation, minification and linting are available as grunt plugins. As long as a plugin is specified in package.json as a dependency, and has been installed via npm install, it may be enabled inside your Gruntfile with a simple command:

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

Custom tasks

You can configure Grunt to run one or more tasks by default by defining a default task. In the following example, running grunt at the command line without specifying a task will run the 'jshint' task. This is functionally the same as explicitly running grunt jshint or even grunt default. Any number of tasks (with or without arguments) may be specified in the array.

 grunt.registerTask('default', ['jshint']);

If your project requires tasks not provided by a Grunt plugin, you may define custom tasks right inside the Gruntfile. For example, this Gruntfile defines a completely custom default task that doesn't even utilize task configuration:

module.exports = function(grunt) {

  // A very basic default task.
  grunt.registerTask('default', 'Log some stuff.', function() {
    grunt.log.write('Logging some stuff...').ok();
  });

};
 
Custom project-specific tasks don't need to be defined in the Gruntfile; they may be defined in external .js files and loaded via the grunt.loadTasks method.


 After all this configuration, creation of project, adding package.json and Gruntfile.js, defining initConfig and grunt plugin and tasks you just need to run grunt command

The output expected:
$ grunt
Running "jshint:src" (jshint) task
>> 1 file lint free.

Done, without errors.


To run specific task, you can also run grunt command with argument,
$ grunt test

Where test is registered task in grunt.