Creating a grunt task

In our las part of this series I showed how to get a simple grunt task to run. In this tutorial we will look at how to create and configure your own tasks. To do so we will look at how we would setup an image optimization task.

You can download all files used here: http://bit.ly/schurpf-create-grunt-task

Find an image optimization task

We will use a task somebody else wrote for us. The easiest way to find this task is to just google: grunt image optimization. The first link that shows up for me is: https://github.com/gruntjs/grunt-contrib-imagemin. We will us this for this example.

Alternatively you can search directly in https://npmjs.org/

or way geekier type the following in your command line:

$ npm search gruntplugin image optimization

#GeekOut #TooCoolForSchool

Setup package.json

Our next task is to create a package.json file. Open a terminal in the folder you want your grunt files in. To create a package.json file I usually just run the command

$ npm init

and just hit enter all the way through.I go into the file and delete the main, script and license. After that I fill out the rest of the fields (you don’t have to).

Here is what my package.json looks like in the end:

{
  "name": "grunt_task",
  "version": "0.0.0",
  "description": "Grunt file for grunt task tutorial",
  "author": "schurpf"
}

Intall grunt

In the open terminal, I run

$ npm install grunt –save-dev

Note! it is –save-dev with two -, -. If you copy paste this may cause an error!

This will update your package.json file and make grunt available in this project.

Intall imagemin

We will follow the instruction from github and run

$ npm install grunt-contrib-imagemin –save-dev

This will download us all we need to run the image optimization task.

Create and configure your Gruntfile.js

We are getting close, now it is time to create our Gruntfile.js. Create a new file called Gruntfile.js and past the following code in there:

module.exports = function(grunt) {
  // set up grunt
};

This is the base of a standard Gruntfile.

Note for mac users: I usually type in the terminal:

$ touch Gruntfile.js

I than open the file via finder.

Configure the imagemin task

We are close, we need to configure our task, to do so I copy the sample configuration from github into my Gruntfile.js.

grunt.initConfig({
  imagemin: {                          // Task
    static: {                          // Target
      options: {                       // Target options
        optimizationLevel: 3
      },
      files: {                         // Dictionary of files
        'dist/img.png': 'src/img.png', // 'destination': 'source'
        'dist/img.jpg': 'src/img.jpg',
        'dist/img.gif': 'src/img.gif'
      }
    },
    dynamic: {                         // Another target
      files: [{
        expand: true,                  // Enable dynamic expansion
        cwd: 'src/',                   // Matches relative to this path
        src: ['**/*.{png,jpg,gif}'],   // Actual patterns to match
        dest: 'dist/'                  // Destination path prefix
      }]
    }
  }
});

grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);

 

We need to make a few changes:

  • remove target “static”
  • remove cwd line in target dynamic
  • remove exand: true in target dynamice
  • change src in target dynamic to match the folder you want optimized

After those changes my Gruntfile.js looks like this:

module.exports = function(grunt) {
  grunt.initConfig({
  imagemin: {                          // Task
    dynamic: {                         // Another target
      files: [{
        expand: true,                  // Enable dynamic expansion
        src: ['images_orig/*.{png,jpg,gif}'], // Patterns to match
        dest: 'dist/'                  // Destination path prefix
      }]
    }
  }
});

grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);
};

Run grunt

Switch to your command line and type

$ grunt

Sit back relax and enjoy the magic :). In my case the images went from 1.8mb to 1.3mb. Pretty nice little image optimization. The best part about all this is that you will now literally be able to do this in all your projects.

If you didn’t do so, you can download all files used here: http://bit.ly/schurpf-create-grunt-task.

Is everything clear? Pls let me know in the comments below if one of the steps does not work.

5 Steps to running your first Grunt task – Beginner Grunt Tutorial

This is my beginner grunt tutorial to get you started with grunt as simple as possible. I will show you in 5 steps how to get your first Grunt task to run. The task we picked here is to minify a js file. All the files to run this demo can be found at:
Download
Download
Download

This demo uses the same code as: http://gruntjs.com/getting-started.

Abbreviations for the Beginner Grunt Tutorial

These are the abbreviations I use during this tutorial:

cmd: Command line.

$ This command is typed in your command line

Beginner Grunt tutorial in 5 steps

  1. Install node.js http://nodejs.org
  2. Install Grunt command line (CLI)

    npm install -g grunt-cli

  3. Go to your root folder of your project. Save files: Download, Download and Download (sample file).
  4. Use npm install to get grunt and all dependencies via your cmd. Make sure you are in the same folder you saved all the 3 files from step 3.

    npm install

  5. Run grunt in cmd

    grunt

You have successfully run your first Grunt task!

Did this work for you? Please let me know in the comments below. If you ran into a problem pls check out the troubleshooting below.

5  Steps to running your first Grunt task video

(coming soon)

Trouble Shooting the 5 steps

Here are the same steps as above, but this time with hints on how to check whether you completed a step. I will use

To demonstrate what method you can use to check whether your system performed a step correctly.

I will use the symbol $ to showcase what command to type in your cmd.

$ command in cmd

and no $ to showcase what the output may look like.

sample output

  1. Install node.js http://nodejs.org

    $ node -v

    v0.10.24

  2. Install command line interface

    npm install -g grunt-cli

    $ grunt –version

    grunt-cli v0.1.11

  3. Go to your root folder of your project. Save file: package.json, Gruntfile.js and my_code.js
  4. Install all dependencies in cmd in the same folder you saved package.json

    npm install

    $ grunt –version

    grunt-cli v0.1.11

    grunt v0.4.2

  5. Run grunt in cmd

    grunt

    File my_code.min.js got created

Still not working? Please let me know in the comments below.

Next steps with Grunt

The next step is to learn how to setup your own Grunt tasks. Should you be interested in WordPress Frontend Developer Tools, check this out.