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

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.

 WordPress Homepage Pagination Problem with WP PageNavi
I am at hart a valuepreneur with a big entrepreneur drive, passionate programmer, hard worker and semi retired poker pro. I am dedicated, eager and very goal oriented. My analytical and rational thinking allows me to be a phenomenal thinker and problem solver.

Solving problems is what makes me happy.

Contact me for your custom WordPress solution.

Leave a Reply

Your email address will not be published. Required fields are marked *