Using Grunt With Web Projects

From Littledamien Wiki
Revision as of 17:48, 7 November 2013 by Video8 (talk | contribs) (→‎Configuration)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.json specifies the project properties and its Grunt library dependencies.
  • gruntfile.js configures 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']);

};

See also