Minify javascript using grunt task runner

Very Generic question for javascript developers is..

How you will manage if you are using large size js file??

This is soo common question for everyone..and for of you know i knew the answer in simple words like just “grunt”. Apart from that i donno anything literally 😉

Know after doing some small junky research i figured it out that we can do minify javascript using grunt/google closure

Lets start digging…

Prerequisites are node.js

First thing you have to know is grunt is a task runner..

1. You can create a new grunt by first installing grunt with your package.json(This file is used by npm to store metadata for projects published as npm modules.) like shown below..

{ “name”: “my-project-name”, “version”: “0.1.0”, “devDependencies”: { “grunt”: “~0.4.5”, “grunt-contrib-jshint”: “~0.10.0”, “grunt-contrib-nodeunit”: “~0.4.1”, “grunt-contrib-uglify”: “~0.5.0” } }

2. Know about grunt file
The Gruntfile
The Gruntfile.js or 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

3. Example

module.exports = function(grunt) {

// Project configuration.


pkg: grunt.file.readJSON(‘package.json’), // read json file

uglify: {

options: {

banner: ‘/*! <%= %> <%=“yyyy-mm-dd”) %> */\n’ }, //Here, the banner option is specified, along with a single uglify target named build that minifies a single source file to a single destination file.

build: {

src: ‘src/<%= %>.js’,

dest: ‘build/<%= %>.min.js’ }



// Load the plugin that provides the “uglify” task.


// Default task(s).

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


4. Create some custom task

module.exports = function(grunt) {

// A very basic default task.

grunt.registerTask(‘default’, ‘Log some stuff.’, function() {

grunt.log.write(‘Logging some stuff…’).ok();




Summary: You can create a custom task like grunt.registerTask(‘test’, ‘Log some stuff’, function() {}); and call ‘test’ task like grunt test in cmd and can see the log. Else simply by using uglify you can minified your source js file to minified js file. In depth there is a lot..but where i listed some basic points for understanding.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s