Manage your application build with Grunt

image.jpg

It can be tricky to manage your web application build. A typical website has css, less, html, image, and js files at minimum. In order to speed up page-load times, these various files are often minified and concatenated. As a developer, it's tedious and time-consuming to to manually post-process each of these files for production.

Node and Grunt combine to make this process much easier. Node is a JavaScript runtime environment, and Grunt is a command line build tool that runs in the Node environment. Grunt uses plugins to accomplish various tasks like minifying, concatenating, and linting. Each plugin does one thing, and there are literally thousands of plugins to choose from.

Instlling Node and Grunt

The installation documentation for both Node and Grunt are both excellent, so instead of rehashing here, we'll just point you to those sites.

First, install Node by following the instructions on the Node Installation Page. This will install the Node Package Manager (npm) as well.

Then follow the instructions on the Grunt Getting Started Page to install the Grunt Command Line Interface (CLI), install Grunt, create a Grunt project, and create a Grunt File.

Customize Your Grunt build

If you followed the instructions above, you'll have a file named gruntfile.js in your project folder. This is a configuration file that tells Grunt which plugins to run. Browse the Grunt Plugins to find plugins for tasks you'd like to run, chances are there is an existing plugin for it.

A Simple Gruntfile

The code below represents a simple Grunt file that will concatenate three files into one using the grunt-contrib-contact plugin, and then minify that file using the grunt-contrib-uglify plugin.

gruntfile.js

module.exports = function (grunt) {
    'use strict';
     
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify'); 

    grunt.initConfig({
      concat: {
        dist: {
          src: ['src/intro.js', 'src/project.js', 'src/outro.js'],
          dest: 'src/combined.js',
        },
      },  
      uglify: {
        my_target: {
          files: {
            'dest/output.min.js': ['src/combined.js']
          }
        }
      }
    });

  grunt.registerTask('default', ['concat', 'uglify']);
};

It's easy to initiate the processing of a Gruntfile. Just type 'grunt' on the command line and grunt will will execute the steps defined in gruntfile.js.

Integrate Grunt into Your Workflow

As you become more familiar with Grunt, you'll want to integrate more Grunt Plugins into your workflow. It will take slightly more effort up-front, but the payoff will be worth it as you'll need fewer steps to generate production-ready code, your site will be faster, and your code cleaner.