What is Grunt?
Grunt is a command line task runner; i.e a build tool.
Grunt is supposed to be used with node.js installation. It is built on top of node. Grunt is available as a package at npm repository.
Two Purpose of Grunt
The major purpose of Grunt is automation. The following are two main reasons to use Grunt:
1. Build Projects
Execution of all the build tasks in single command for javascript projects. When you are working on a Java project, you might use Ant for build.
When you are working on a project which is javascript centered, you may need to get hint from the javascript files to ensure the coding standards are met, or may need to concatenate it, or minify it, or uglify it.
If it is a user interface development project, then you may need to get hints from the css files, concatenate it, split it, minify it or may need to convert SASS files to css and lot more.
All the tasks mentioned above is to be done before each build. In this case, we can use grunt as build tool, which can be configured to carry on all these build tasks in a single command.
2. Automate Tasks
Running repeated tasks automatically on file inundation/modification. Again the tasks mentioned above may have to be done repeatedly on development environment after each inundation or modification of the file you are working on.
Here you can use grunt to take care of this automatically in the background as soon as file is updated and saved.
Install and Configure Grunt
1. Install Node.js
First, we will need to have Node.js installed on the system.
Download Node.js from here, and do the standard installation.
From the above link you will find setup files for all operating systems. When you install Node.js, you’ll also get npm along with it.
2. Install grunt-cli
From the command line, execute the following to install Grunt CLI:
npm install -g grunt-cli
The above command will globally install the grunt command line interface from npm repository.
3. Setup NPM Project
Now get into your project folder, and setup a npm project with all required packages, while getting the configuration from package.json file.
Initiate a npm project by following command:
npm init
The above command will create a package.json file in your local folder. It will ask you for some basic identifiers to be set in the json file.
You can open the “package.json” file and see the initial json created there. You can also edit the entries in that file or remove unwanted ones.
4. Add Packages
Open the “package.json” file and add the packages you need to install with the key “devDependencies” in the json. It will be look something like the following:
{ "name": "Some name as set by you", "version": "0.3.14", "description":"Some description given by you", "author":"Your name", "license":"As given by you" }
In the above json, now add a new key-value pair as shown below.
The values associated with the key “devDependencies” is the packages which you want to install. Keeping the package name with ‘~’ as prefix ensures that in upcoming steps while installing these packages by npm, the latest version of the package will be installed. Here we are going to use only one package for css minification for an example demonstration.
{ "name": "Some name as set by you", "version": "0.3.14", "description":"Some description given by you", "author":"Your name", "license":"As given by you", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-cssmin":"~0.10.0" } }
5. Install grunt-contrib-cssmin
Execute the following command:
npm install
You will see the log similar as below after running the above command from which indicates what all packages have been installed.
npm WARN package.json SomeName@0.3.14 No repository field. npm WARN package.json SomeName@0.3.14 No README data grunt@0.4.5 node_modules\grunt +-- dateformat@1.0.2-1.2.3 +-- which@1.0.5 +-- eventemitter2@0.4.14 +-- getobject@0.1.0 +-- colors@0.6.2 +-- grunt-legacy-util@0.2.0 +-- hooker@0.2.3 +-- rimraf@2.2.8 +-- async@0.1.22 +-- exit@0.1.2 +-- lodash@0.9.2 +-- coffee-script@1.3.3 +-- underscore.string@2.2.1 +-- iconv-lite@0.2.11 +-- grunt-legacy-log@0.1.1 (underscore.string@2.3.3, lodash@2.4.1) +-- glob@3.1.21 (inherits@1.0.0, graceful-fs@1.2.3) +-- nopt@1.0.10 (abbrev@1.0.5) +-- minimatch@0.2.14 (sigmund@1.0.0, lru-cache@2.5.0) +-- findup-sync@0.1.3 (lodash@2.4.1, glob@3.2.11) +-- js-yaml@2.0.5 (esprima@1.0.4, argparse@0.1.15) grunt-contrib-cssmin@0.10.0 node_modules\grunt-contrib-cssmin +-- chalk@0.4.0 (ansi-styles@1.0.0, has-color@0.1.7, strip-ansi@0.1.1) +-- clean-css@2.2.7 (commander@2.2.0) +-- maxmin@0.2.2 (figures@1.0.2, pretty-bytes@0.1.1, chalk@0.5.1, gzip-size@0.2. 0)
The above command will read the “package.json” file and will install all the dependencies listed there locally. You can also install the packages directly without any prior entry in “package.json”.
Use the following command to do so:
npm install grunt-contrib-cssmin –save-dev
The above command will also update the “package.json” file with the entry of the package you are installing.
6. Setup Grunt File
Now, set up the Grunt file by creating a file callled “Gruntfile.js”.
// Creating a wrapper module.exports = function(grunt){ // Initializing configuration objects grunt.initConfig({ // Reading 'package.json' so that we can use setting given there pkg : grunt.file.readJSON('package.json'), // specifying the settings for css file minification cssmin : { minify : { expand : true, cwd : 'project/css/', src : [ '*.css', '!*.min.css' ], dest : 'project/css/', ext : '.min.css' } } }); // Loading the 'grunt-contrib-cssmin' package. grunt.loadNpmTasks('grunt-contrib-cssmin'); // Registering css minification as a default task grunt.registerTask( 'default', [ 'cssmin' ] ); }
In the above json while going through the comments you can understand the following points:
a) All the grunt configuration should be inside a wrapper function as follows:
module.exports = function( grunt ){ // Do all the project code related to grunt inside this function }
b) Set up all the configuration for the required tasks in “grunt.initConfig( )” method. As we can see in the snippet below from the “Gruntfile.js”.
grunt.initConfig({ // Reading 'package.json' so that we can use setting given there pkg : grunt.file.readJSON('package.json'), // specifying the settings for css file minification cssmin : { minify : { expand : true, cwd : 'project/css/', src : [ '*.css', '!*.min.css' ], dest : 'project/css/', ext : '.min.css' } } });
c) We have to load the installed packages to use it inside the wrapper function. We can load it using “grunt.loadNpmTasks( )” method. For example: grunt.loadNpmTasks(‘grunt-contrib-cssmin’);
d) We have to register the task so that we can run it from command line. Use “grunt.registerTask( )” method for that. For example:grunt.registerTask( ‘default’, [ ‘cssmin’ ] );
In the lines above ‘default’ parameter registers ‘cssmin’ as default task to be executed while typing simple “grunt” without any task name proceeding, as a command.
You can register a task using a name and mention it explicitly while using “grunt” command. For example: grunt.registerTask( ‘minifycss’, [ ‘cssmin’ ] );
Now, We can run the command “grunt minifycss” in terminal/command prompt to execute explicity the css minification task.
e) You can read a json file using “grunt.file.readJSON( )” method. You may need to use some values from ‘package.json’. If you are not using it you can remove these lines.
7. Register Grunt Task
Finally, save the “Gruntfile.js” and cd into the directory where “Gruntfile.js” is located.
From here, execute the following command to get your task registered as ‘default’.
grunt
Type the following command to get your task registered as ‘firstParameter’
grunt firstParameter