Reference
Installation
Lets install the Grunt CLI globally so we can access the “grunt” command.
npm install grunt-cli -g
check and make sure Grunt is installed correctly
grunt --version
Note that installing grunt-cli does not install the Grunt task runner! The job of the Grunt CLI is simple: run the version of Grunt which has been installed next to a Gruntfile. This allows multiple versions of Grunt to be installed on the same machine simultaneously.
Project Integration
Integrate Grunt with our project. package.json
{
"name": "my-project-name",
"version": "0.1.0",
"devDependencies": {
"grunt": "~0.4.2",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-nodeunit": "~0.2.0",
"grunt-contrib-uglify": "~0.2.2"
}
}
A Gruntfile is a JavaScript file that Grunt leverages to understand your projects tasks and configuration. When you run “grunt” from the command line, Grunt will recurse upwards till it finds your Gruntfile. This functionality allows you to run Grunt from any sub directory of your project.
Gruntfile.js
A Gruntfile is comprised of the following parts:
- The “wrapper” function
- Project and task configuration
- Loading Grunt plugins and tasks
- Custom tasks
This is the basis of a Grunt file, it’s a wrapper function that takes in “grunt” as an argument. This allows us to register tasks and configuration with grunt (and leverage Grunt’s APIs) before Grunt actually runs any tasks
module.exports = function(grunt) {
// set up grunt
};
Automate The Grunt Work
JSHint
npm install grunt-contrib-jshint --save-dev
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
src: ['Gruntfile.js', 'src/app/**/*.js', 'src/config.js', 'tests/app/**/*.js'],
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
globals: {
require: true,
define: true,
requirejs: true,
describe: true,
expect: true,
it: true
}
}
}
});
// Load JSHint task
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task.
grunt.registerTask('default', 'jshint');
};
run grunt
$ grunt
Running "jshint:src" (jshint) task
Lint free.
Done, without errors.
OR :
$ grunt jshint
Running "jshint:src" (jshint) task
Lint free.
Done, without errors.
grunt “watch” task
npm install grunt-contrib-watch --save-dev
grunt.initConfig({
watch: {
files: '<%= jshint.src %>',
tasks: ['jshint']
},
});
grunt.loadNpmTasks('grunt-contrib-watch');
This tells the grunt “watch” task (a built in task), to run the “lint” task every time one of the configuration specified lint files changes