As developers, the more we can automate repetitive tasks, the more time we have to do fun things. Grunt can watch, minify, compile, lint, clean, test, and perform countless other tasks - automatically. There are literally hundreds of grunt plugins. It’s easy to configure and once it’s up and running will save you time and effort, more efficiently than an actual grunt. Note to self, write a grunt plugin to make a cup of coffee.
I’m just going to cover the basics here for now.
Getting the ball rolling
The Grunt CLI
Assuming you’re a serious developer, you’ll already have nodejs installed (and npm, which now comes with it by default). If not, Google it and get it installed. Once you’re ready, run:
You can now run “grunt” from anywhere. Happy times.
It uses 4 plugins, which need to be referenced in the package.json (devDependencies) and your Gruntfile.js:
You can then define some tasks in your Gruntfile.js, here’s my jasmine task from functional.js that uses grunt-contrib-jasmine.
The configuration for a task is specified as a property on a configuration object, with the same name as the task. This example takes the functional.min.js source and runs the specs in spec.js.
You can run it by doing:
In the above example, it’s unlikely that you’ll just want to run one task at a time, such as jasmine. I regularly want to lint and minify before running tests. Fortunately with grunt, it’s easy to combine your tasks:
This will run the jshint task, the uglify task and then the jasmine task, in that order.
Watching for changes
I’m addicted to automation, give me more! You won’t want to keep typing “grunt test” and various other commands, even when you have combined tasks. This is where the Grunt watch plugin comes into play. You can configure watch so that it will trigger tasks as soon as files are modified:
and code in my happy place until I hear an unexpected beep that something is wrong. Ahh, automation.