Skip to Content

Devin Clark

Grunt: A Tool for the Modern Web Artisan

Automate Everything; a philosophy we should all strive for as developers. Grunt can help with this and I would like to help you learn how to properly utilize it.

Have you ever… compiled Compass/Sass, used Autoprefixer on CSS, concatenated JavaScript or CSS, minified JavaScript or CSS or linted JavaScript or CSS manually? Well you’re wasting a lot of time. Grunt can do all of these (and more) with one command or even when you save a relevant file.

Installing Grunt

Grunt and all of its tasks are node modules on NPM so installation is as easy as npm install -g grunt-cli. Don’t get too excited; this is just the global command for grunt.

Now we need to open out project directory in a terminal window and run npm install grunt --save-dev. If you don’t already have a package.json file in your project, run npm init first. I usually just hit enter through the fields and change them later. Now we are up and running …sort of.

Grunt has hundreds of plugins that you install via NPM. I would recommend you install them with the --save-dev option so they will be stored in your package.json file. This will allow other developers to take your project, run npm install and be ready to go.

Using Grunt

Let’s dive in with some code. I am going to include a sample Gruntfile at the bottom of the post that I used in a recent project. Here is a very minimal example to get you started. Place this code in Gruntfile.js.

module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);

grunt.initConfig({
jshint: {
all: ['js/*.js'],
},
});

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

You might notice this line require('load-grunt-tasks')(grunt); and wonder what kind of madness that is. This is a brilliant Grunt plugin called load-grunt-tasks that loads in all the tasks automagically so you don’t need a line to require each task. To install, just run npm install --save-dev load-grunt-tasks.

For this task to work, you will need to run npm install grunt-contrib-jshint --save-dev. Then you can run grunt and it will run jshint on your all the js files in the js directory. Every task I’ve seen includes sample(s) of this code in the README.

As promised, here is the link to my boilerplate Gruntfile.

Thanks for reading. If you have any questions or comments please leave a comment below and I will try my best to address it. In the future, I would like to cover grunt-init, a scaffolding tool.

Photo of Devin Clark
Devin Clark
Principal Software Engineer, Oracle
You Might Also Like