Gruntjs JavaScript Task Runner

Gruntjs is a really handy tool for automating common web design and development tasks such as concatenating, minifying and linting files.

We’ve adopted Gruntjs for our build process, using it to firstly to watch our SASS and JavaScript files for changes and when a change is detected, i.e. someone has updated a file it triggers a series of tasks starting with, in the case of a change in a SASS (.scss) file, the compilation of SASS into CSS via Compass and then the minification of the resulting CSS file.

In the case of JavaScript the first task triggered is the concatenation of several JavaScript files into one and then the minification of the resulting file. It’s easy to configure Gruntjs to action this on all the files in a particular folder so you don’t have to update the Gruntfile each time you add a new JavaScript file.

The next step is unique to our particular set-up but we then update our HTML templates with a date/time stamped filename for the file that has changed, for example:

<script src="http://ia3.edcdn.com/_/script.1363276140065.js"></script>

This is because our JavaScript and CSS files are served via Amazon’s Cloudfront CDN with far future expiry so they are effectively cached by the visitors browser forever. That’s great for performance but when we want to make changes we have to alter the filename to bust the visitors cache. Without doing that the visitor would just be accessing the same cached copy on subsequent visits to the website even if the file has been updated.

We also use Gruntjs to lint our files, this is useful as it identifies any common mistakes and syntax errors and helps to enforce good coding practices.

The other areas where Gruntjs has also excelled is compressing our images, using the Gruntjs plug-in “contrib-imagemin” we’ve set-up tasks to lossly compress the images used in our sites using jpegtran and optipng.

Gruntjs is still relatively new but it’s being developed at a very rapid pace as it’s clearly fulfilled a need of many web designers and web developers and as a result quickly gained popularity.

Yeoman, which is a workflow / project scaffolding tool from Google (definitely worth a look), uses Gruntjs extensively and has helped to boost its popularity further.

A good place to start with Gruntjs is by taking a look through the available plug-ins as they will likely trigger your imagination as to the myriad of tasks you could potentially automate with it. The “contrib” plug-ins that currently show at the top of the list are those that are maintained and contributed by the Gruntjs core team.

Here’s a list of the plug-ins we’ve used in our build script:

  • contrib-compass
  • contrib-uglify
  • contrib-watch
  • contrib-concat
  • contrib-imagemin
  • contrib-jshint
  • contrib-csslint

Tagged with:

You might also like...

GitLab Review

Michael Walsh by Michael Walsh