Grunt.js

Super high-level overview of my 
favorite tool of the year

Who am I?


  • Shane Pfaffly

  • Lead Interactive Web
    Developer @ MMGY

  • Always looking for ways to be lazy 
    automate menial tasks

  • Twitter: @spfaffly

What is Grunt.js?


  • Website defines it as a task runner
    built with JavaScript.

  • A build tool. Compared to Ant or Maven.
     
  • An automation tool. Which allows
    you to run just about anything you want.

  • But I like to refer to it as a "workflow" tool.

First steps...

(Assuming you have Node installed)

Install the Command Line Interface (CLI)

  • Grunt and all Grunt plugins are managed through npm, 
    Node.js Package Manager

  • Run the following command through npm to install Grunt.js
    command line interface:
sudo npm install -g grunt-cli

Note: This isn't Grunt.js itself. This just helps manage your
multiple versions of Grunt on your machine.

Prelude...


Two files needed to set up Grunt.js in your project.

  • package.json - File used by npm to store metadata about
    projects. Its biggest use is to help manage dependencies used
    by your Grunt.js task.

  • Gruntfile.js - Configures/defines tasks and load grunt plugins.

  • Both files live together at the root of your project.


Preparing your first
Grunt.js project...


// create package.json
$ npm init 
// install grunt 
$ npm install grunt --save-dev
// install grunt plugins
$ npm install grunt-contrib --save-dev

Note: The --save-dev flag will help manage your
dependencies in the package.json file.

Note2: The last command will install all grunt-contrib plugins.

package.json...


{
  "name": "gruntdemo",
  "version": "0.0.1",
  "description": "Grunt.js demo",
  "author": "Shane Pfaffly",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-concat": "~0.3.0",
    "grunt-contrib-sass": "~0.5.0",
    "grunt-contrib-copy": "~0.4.1",
    ...
    "grunt-contrib": "~0.8.0"
  }
}
End up with this package.json file. 

Notice the dependencies!

Gruntfile.js...

Comprised of:

  • The "wrapper" function

  • Project and task configurations

  • Loads Grunt.js plugins and tasks

  • Custom tasks defined by you!

Example of Gruntfile.js...


Note: Example pulled from Grunt's website. More on this later...

You should now have...




Welcome to the
Grunt.js wrapper function...

All Grunt code is housed in this function:


module.exports = function(grunt) {
  // Do grunt-related things in here
};

Configuring tasks...

  • Task configuration is specified in your Gruntfile via the
    grunt.initConfig method.

grunt.initConfig({
        taskName: {
            targetName: {
                // configuration
            }
        }
    });
taskName is related to the task you want to configure
such as watch, sass, uglify and jshint.

Configuring tasks options...


  • Inside a task configuration, an options property may be
    specified to override built-in defaults.
grunt.initConfig({
        uglify: {
            options: {
                // custom uglifyjs options
            },
            development: {
                // configuration
            }
        }
    });

Creating custom tasks...


Defining a new default task:
// Default task(s).
grunt.registerTask('default', ['uglify']);

You can override the "default" task with a custom task like above.

Now you can then run call the "grunt" command directly and the
previous task will run automagically.

This new custom task is the same as running "grunt uglify"
or even "grunt default".

Caveat...

Defining the actual tasks can be placed outside the
Gruntfile.js file and loaded in using grunt.loadTasks method.
This keeps the Gruntfile.js easier to maintain and light weight.
 
module.export = function (grunt) {
  grunt.initConfig({
    ...
  });
  // load js files in ./tasks
  grunt.loadTasks('./tasks');
  ...
}




Some super-useful
grunt plugins...

grunt-contrib-watch

"Run predefined tasks whenever watched file patterns are added, changed or deleted."

grunt.initConfig({
    ...
    watch: {
      js: {
        files: ['**/*.js'],
        tasks: ['jshint'],
        options: {
          spawn: false,
        }
      }
    }
  });
The above watches *ALL* js files in a project and runs the
jshint task if any js files are moved, modified or deleted.

grunt-contrib-imagemin

"Minify PNG, JPEG and GIF images"

grunt.initConfig({
    ...
    imagemin: {                          // Task
      dynamic: {                         // Another target
        files: [{
          expand: true,                  // Enable dynamic expansion
          cwd: 'src/',                   // Src matches are relative to this path
          src: ['**/*.{png,jpg,gif}'],   // Actual patterns to match
          dest: 'dist/'                  // Destination path prefix
        }]
      }
    }
  });
The above scans for all png, jpg and gif files in the "src" folder and minifies/compresses the images to the output folder of "dist".

grunt-contrib-sass

"Compile Sass to CSS"

// Project configuration.
  grunt.initConfig({
    ...
    sass: {
      dist: {
        files: {
          'styles/styles.css': 'styles/sass/styles.scss'
        }
      }
    }
  });
The above task compiles a defined styles.scss file to its
corresponding styles.css file.

Note: This task bundled with grunt-contrib-watch can build your
Sass files everytime you edit them.


Of course there are 

more plugins...


  • Run simple HTTP servers
  • Run unit tests
  • Convert image assets into sprites
  • Minify CSS/JS files

It's time to say "good bye!"

Here are some links for the road:




Thank You!

Grunt.js

By spfaffly

Grunt.js

  • 2,758