Using Grunt to automate development tasks: Part II

If you’re new to Grunt, or don’t know what it is, check out the first article I wrote which introduces it: Using GRUNT to automate development tasks: Part I

As explained in that first article, Grunt is a javascript task runner. It allows us automate all sorts of tasks, however, we’re still having to trigger a manual process by running Grunt every time we want it to do something.

Using watch, we can get Grunt to run tasks whenever something changes instead. So, for example, every time we update our JS, Grunt will automatically concatenate and minify it to an output file instead of waiting for us to run the file manually.

Watching happens through the official grunt-contrib-watch plugin.

Let’s get this installed as we have done in our previous post (it’s exactly the same process) – npm install grunt-contrib-watch--save-dev.

We configure watch by giving it specific file, or folder (or both) to monitor, then we tell it what tasks we want to run when it detects a change.

So, let’s take a look. I think it would be safe to say that we’d like Grunt to concatinate and minify our JS whenever anything in the js folder changes – not just when we run it; and not when we change some images or CSS.

This should be fairly straight forward. spawn stops Grunt spawning child processes and keeps the context within the main watch function.

Don’t forget to load the NPM Task, and also to register the task.

grunt.loadNpmTasks('grunt-contrib-watch');

grunt.registerTask('default', ['concat', 'uglify', 'imagemin', 'cssmin', 'watch']);

There are a lot of other resources and extensions around Grunt. So, some further reading:

By Douglas Radburn. at 2:39PM on Wednesday, 05 Mar 2014

Doug is our Senior Open Source Web Developer since bringing his knowledge and skills to Branded3 in 2009. A founding developer of our Twitition and Competwition platforms, Doug has also been lead in our Open Source Projects on Magento ecommerce solutions and Wordpress CMS platforms. Follow Douglas Radburn on Twitter.

comments

  • Bret Kerr

    Thanks for the article Douglas. Quick question – do you think it would be possible to automtae, via Grunt, the task of updating .less and .css files, for a Sitecore based site, on 5 different production servers (we code on Macs and upload to 4 different production servers via windows remote desktop).

  • Douglas Radburn

    Hi Brett, Sorry for the delay getting back to you. Our .NET team aren’t currently using GRUNT, as they integrate with LESS in a different way on their Sitecore sites, but let me find out!