GruntJS and automating development tasks

January 7, 2014, 9:16 pm
Author: James Griffiths

Installation

Grunt JS, as of the time of writing, is installed via the command line so you will need some familiarity, no matter how basic, with working in that environment.

The first thing to do is check that Node is installed on your machine as Grunt require this for installing various packages. Simply open up a terminal (we’re using the Mac OS X terminal) and type the following command:

node -v

If Node is installed you should see something akin to the following:

If Node isn’t installed you can download a GUI installer from nodejs.org and follow the installation instructions. If all goes well you should see a screen that looks like the following:

When you’re satisfied that Node is installed the next step is to install Grunt so that it is available in your system path (allowing it to be run from any directory on your machine). This is simply done with the following command typed out in the terminal:

sudo npm install -g grunt-cli

You will then be prompted for your password and, all things being well, you should see the terminal process the command and start running through the installation of Grunt.

If all has gone well then Grunt should be successfully installed which means we can move on to the next step: creating the necessary configuration files to run Grunt against a project build.

Configuring Grunt

In order to use Grunt JS to automate workflow for a project build there are 3 things that need to be done:

  1. Navigate, via the command line, to the root of your project directory
  2. Create the following 2 files: package.json file and Gruntfile.js (which we shall configure shortly)
  3. Run Grunt (more on this later)

Setting up the project

The package.json file will contain information about your project such as name, version, description as well as a list of dependencies that are used by Grunt for automation tasks.

A typical package.json file might look like the following:

 

{ 
    "name": "Saints-at-Play-Limited", 
    "description": "Saints at Play website build", 
    "version": "0.0.1", 
    "homepage": "http://www.saintsatplay.com", 
    "devDependencies": { } 
}

The devDependencies section in the package.json file will contain a list of all grunt related modules that are available for use in your project. As you can see in the above sample declaration this is currently empty. In the next part of the tutorial we’ll show you how to add modules to this section and then configure/load them for use in your project using the Gruntfile that you also created.

Installing, configuring and loading modules

The package.json and Gruntfile that you created will be used to register and configure the specific modules and commands that are used for automating tasks on your website project (more information here: http://gruntjs.com/getting-started).

Using the Mac OS X command line change to where your project directory is located (I.e. cd /Users/your-name/Sites/project-name) and type in the following to install grunt to your project directory:

sudo npm install grunt --save-dev

You’ll be prompted for your password so enter this and, all things being well, you should see the package being requested via the command line and installed.

The --save-dev flag tells grunt to add this to the devDependencies section of your package.json file as well as install the module in your project directory.

If you navigate in the Finder to where the root of your project directory is located you will notice that the following directory has been installed:

node_modules

And inside this directory is a sub-directory titled grunt.

Congratulations! You’ve just installed your first grunt module.

The following screenshot illustrates the different Node modules installed for use by Grunt in a sample project:

In the following section we are going to go through how to installing additional Grunt modules.

Installing additional modules

In this example you’ll be installing the jshint package but installing pretty much any package in grunt follows a similar process.

jshint allows you to determine if there are any errors in how your javascript is structured/written - which is pretty useful as a debugging tool prior to launching for use on a live project.

Returning back to the command line, type out the following:

sudo npm install grunt-contrib-jshint --save-dev

You’ll be prompted for your password so enter this and, all things being well, you should see the package being requested via the command line and installed.

Now you’ve installed 2 modules for use in your project (which have been automatically added to your package.json file devDependencies section) you will need to configure your GruntFile.js to tell Grunt how to implement these modules for use in your workflow.

Type out the following inside your Gruntfile:

module.exports = function(grunt) { 
   grunt.initConfig({ 
      pkg.grunt.file.readJSON(‘package.json’); 
      jshint: { src: [‘Gruntfile.js’, ‘name-of-your-js-file.js’, ‘name-of-another-js-file.js’], 
                options: { // Refer to/copy from the configuration parameters in the example Gruntfile! } 
              } 
   }); 
   grunt.loadNpmTasks(‘grunt-contrib-jshint’); 
   grunt.registerTask(‘default’, [‘jshint’]); 
}

 

So what does all this mean?

The first line is the wrapper function, which is mandatory, that instructs Grunt to run everything contained inside.

The initConfig object defines the configuration data for Grunt and related modules that are being used.

The pkg.grunt.file.readJSON(‘package.json’); line imports the JSON metadata from the package.json file so we can pass certain values from there (such as name, description, author etc) for use in our Gruntfile configuration.

Now we declare the configuration for the jshint module as JSON using jshint: { }. Inside here we define the files that we want to check and configure options for jshint to use.

ALL modules that you install will be configured using a similar syntax.

Then, after this configuration block we load the jshint module using the following declaration:

grunt.loadNpmTasks(‘grunt-contrib-jshint’);

Finally we register the task so that Grunt knows what to run when we call it from the command line:

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

So, by default we want to run the jshint task (which will draw from our configuration earlier in the gruntfile).

You will notice in the example Gruntfile that is included below that a range of tasks have been set to be run by default. This is just an example of how these can be configured and saves having to type out each one separately in the Mac OS X Terminal.

To run this task navigate back to the command line and (ensuring you are still in your project directory) type out the following:

grunt

All things being well (and with no syntax errors) you should see the Mac OS X Terminal indicate the jshint task passed successfully.

In the sample Gruntfile that is attached below we can see what happens when multiple commands are run successfully:

And this is what happens when something goes wrong!

Things to be aware of

You may find, when creating your own Gruntfile, that when you try to run the tasks from the command line all you get back are errors. This is pretty common as Grunt is very strict in terms of what it expects the Gruntfile to contain and how that should be formatted.

Following these rules to minimize errors (and study the example GruntFile attached below - these errors have already been solved for you!)

  • Do NOT use tabs to indent each line, use spaces instead
  • Ensure there are NO spaces or tabs at the end of each line
  • Ensure that each configuration block is terminated with a comma (except for the last configuration block in the series)
  • Format the JSON configuration properly (study the attached Gruntfile to understand the syntax)

Okay, but is that all?

Pretty much! Granted the example file we created isn’t all that impressive but in the attached files you can see configuration options for the following tasks:

  • Linting JS files to check for best practice
  • Concatenating JS files
  • Minifying JS files
  • Minifying and concatenating CSS files
  • Compressing images

Now instead of doing these separately, using different programs/websites, they can all be done in one operation through running a simple command line instruction: grunt.

How timesaving, quick and super-efficient is that?

An absolute must for any project!

Further resources

http://gruntjs.com/getting-started

http://gruntjs.com/sample-gruntfile

https://github.com/gruntjs/grunt-contrib

http://www.jshint.com/docs/options/

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.