Grunt is a "task runner". But what does that mean? Well grunt simplifies things by allowing you to perform a number of tasks with a single command.
This means that you, and your team, can easily enforce coding standards, execute tests, or automate deployment tasks.
So what can use Grunt for?
- Code reloads - Watch
- Linting - JSLint, JSHint
- Testing - Mocha, Jasmine
- Template precompilation - Handlebars
- Deployment tasks - Minify, Combine, Copy
Here is the complete list of grunt plugins that can be used.
So how do you get started?
You start by adding grunt and your desired plugins via npm
or your package.json
file.
{
"name": "testing-grunt",
"version": "0.1.0",
"devDependencies": {
"matchdep": "~0.1.2",
"grunt": "~0.4.1",
"grunt-jslint": "~1.0.0",
"grunt-mocha-cli": "~1.0.6"
}
}
Next you will need to create the configuration file in the root of your project:
vim Gruntfile.js
Inside this file, we create and export a grunt configuration function. Modules are registered and configured in this file.
var matchdep = require('matchdep');
module.exports = function(grunt) {
'use strict';
// loads a task manually
// grunt.loadNpmTasks('grunt-jslint');
// loads all grunt tasks using matchdep
matchdep.filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// create a configuration object
grunt.initConfig({
jslint: {
// jslint configuration would go here
},
mochacli: {
// mocha configuration would go here
}
});
// register tasks that you can call
grunt.registerTask('lint', 'Runs linting', ['jslint']);
grunt.registerTask('validate', 'Runs linting and testing', ['jslint', 'mochacli']);
}
The above configuration file for grunt will allow you to execute two functions lint
and validate
. You can specify which of the configurations are run for each command. The end result is that you can execute linting and testings by runing
grunt validate
Pretty cool! So that's the grunt basics. The more challenging part is configuring the actual plugins how you want. I'll show that in other articles.