Using Grunt to minify javascript

Hackered
Monday, August 25, 2014
by Sean McAlinden

This is a little tutorial for setting up Grunt to minify JavaScript.   Firstly ensure you have installed node.js and grunt onto your machine.

packages.json

First lets create the packages.json file. This file lists all the packages we want to grunt to use. I will be using uglify to minify my javascript and watch to automatically run grunt if certain files change. Navigate to the root of your application using a command line utility and run the following: npm initThis will run a little command line wizard for creating the packages.json file. You will be asked a number of questions such as the name of the app, the version etc. You can edit any of these directly within the file so don't worry if you make mistakes or want to change your mind. My packages.json looks like the following:

{
  "name": "MyGruntSetupTestApp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Sean McAlinden",
  "license": "BSD-2-Clause"
}

Add the following dev dependencies:

"devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-uglify": "~0.5.0"
  }

You file should now look like:

{
  "name": "MyGruntSetupTestApp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Sean McAlinden",
  "license": "BSD-2-Clause",
  "devDependencies": {
    "grunt": "~0.4.5",
    "grunt-contrib-uglify": "~0.5.0"
  }
}

Basic Grunt File

At the root of your project create a file called Gruntfile.js and add the following javascript code:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json')    
  });
};

This is the grunt wrapper function with the package.json configuration file location setup.  

Uglify

The next step is to add uglify to minify some javascript. In my solution I have a file called myTestJsFile.js within a folder called "Scripts". which I would like minifying. The javascript code in the file is:

function blah(someText) {
    var lowerCasedString = someText.toLowerCase();
    alert(lowerCasedString);
}

We need to alter the Gruntfile.js init config to include the following javscript:

uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'Scripts/myTestJsFile.js',
                dest: 'Scripts/myTestJsFile.min.js'
            }
        }

This script sets up the src of the script and the destination to create the minified version. It also sets up a comment banner at the start of the minified file. We also need to load the uglify plugin and register the uglify task. Your code should now look like the following:

module.exports = function(grunt) {
 
    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        uglify: {
            options: {
                banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
            },
            build: {
                src: 'Scripts/myTestJsFile.js',
                dest: 'Scripts/myTestJsFile.min.js'
            }
        }
    });
 
    // Load the plugin that provides the "uglify" task.
    grunt.loadNpmTasks('grunt-contrib-uglify');
 
    // Default task(s).
    grunt.registerTask('default', ['uglify']);
};

Lets give it a try

Navigate to the root of the application using a command line utility and run: npm install This will install grunt and any other dependencies required for running grunt.   Providing there are no errors, now type the following at the same location to run grunt: grunt Providing all has gone well you should receive a message stating: Done, without errors.If you navigate to the scripts folder, you will now see a minified version of the javascript:

/*! MyGruntSetupTestApp 2014-08-25 */
function blah(a){var b=a.toLowerCase();alert(b)}

To minify multiple files you can swap out the build: config for the following syntax:

dist: {
    files: {
        'js/test.min.js': 'js/test.js',
        'js/test2.min.js': 'js/test2.js'
    }
}

There are loads more plugins available for use with Grunt which I'll have a play with and create some more posts soon.