In the world of web-development, automation tools are a great way to save time, improve code and get rid of pesky little tasks that need to be done each and every time (such as hinting your Javascript code, refreshing the browser etc..).

Grunt offers many plugins for all sorts of tasks.

from the gruntjs.com website:

In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc, the easier your job becomes. After you’ve configured it through a Gruntfile, a task runner can do most of that mundane work for you—and your team—with basically zero effort.

In this introduction Ill show how to setup a basic grunt project.

Grunt and Grunt plugins require Node.js and npm

we must first install the grunt-cli

npm install -g grunt-cli

Lets create a project dir, and install grunt using npm:

mkdir grunt-test && cd $_
npm init
npm install grunt --save-dev
npm install grunt-contrib-jshint --save-dev

‘npm init’ will create a package.json file for us, prompting for some information. we can just hit enter untill it’s done for now.

after which we install grunt and grunt-contrib-jshint. we’re telling npm to save the dependencies to package.json with –save-dev.

now that we have a package.json ready, we will need a Gruntfile.js. this file will hold the actual tasks and logic of our project.

create the Gruntfile.js manually, with this content:

module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      all: ['Gruntfile.js', 'testfile.js']
    }
  });
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.registerTask('default', ['jshint:all']);
};

note that we are telling jshint what files to work on, also we are loading the jshint task,

and registering the ‘default’ task (when typing ‘grunt’ in the console).

Now create a file named ‘testfile.js’, put some javascript code in it, and run:

grunt

from the commandline.

Grunt will hint both files, Gruntfile.js and testfile.js, and report back.

the outcome should look something like this:

nitsan@nitsan-b:~/projects/testing/grunt-test
> grunt
Running "jshint:all" (jshint) task
>> 2 files lint free.

Done, without errors.


Finding other plugins

there are many plugins to choose from, some of my favorites are jshint, watch, sass, clean. you can see the list on Grunt’s website: here.

Have fun automating !

⤧  Previous post Create Sublime Text Snippets