Using Grunt With Web Projects
Overview
Configuration and application of Grunt with web projects.
Configuration
See also Grunt prerequisites
Preparing a new Grunt project
Installation depends on creating two files, package.json and gruntfile.js, in the project directory.
package.jsonspecifies the project properties and its Grunt library dependencies.gruntfile.jsconfigures the Grunt tasks.
The easiest way to install Grunt and Grunt plugins is with
$ npm install <module> --save-dev
The --save-dev option updates the package.json file with the module name and version.
Workflow
N.B. while all of the npm commands will work fine in the git bash, cygwin, and powershell shells, the grunt command will only work correctly in powershell.
Start at the project's root directory:
$ cd </path/to/project/root>
Create a boilerplate package.json file:
$ npm init
Install the latest version of Grunt for the project:
$ npm install grunt --save-dev
Add the node_modules directory to .gitignore.
Add Grunt plugins as necessary, e.g.:
$ npm install grunt-contrib-uglify --save-dev
Configure tasks in gruntfile.js:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task(s).
grunt.registerTask('default', ['uglify']);
};