---
layout: codelab
title: Using Imagemin with Grunt
authors:
  - katiehempenius
date: 2018-11-05
description: |
  In this codelab, learn how to use imagemin with grunt to optimize JPEG and
  PNG images for faster download.
glitch: imagemin-gulp
related_post: use-imagemin-to-compress-images
tags:
  - performance
---

## Setup the Imagemin Grunt plugin

This Glitch already contains `grunt`, `grunt-cli`, and the `grunt-contrib-imagemin`
plugin. To add the configuration for Imagemin, you'll need to edit your
`gruntfile.js` file.

{% Instruction 'remix' %}
- In `gruntfile.js`, replace the `//Add configuration here` comment
with this code block:

```javascript
imagemin: {
  dynamic: {
    files: [{
      cwd: 'images/',
      expand: true,
      src: ['**/*.{png,jpg}'],
    }]
  }
}
```

This code block tells Grunt which files should be compressed with Imagemin.

- `dynamic` indicates that the list of files to compress will be *dynamically*
  generated by matching the filenames against the specified file pattern.

- The file pattern `{cwd: 'images/', expand: true, src: ['**/*.{png,jpg}']}`
  will match all the JPEG and PNG images in the `images/` directory.

{% Aside %}
Have more questions about this?
You can
[read more about the Grunt file object here](https://gruntjs.com/configuring-tasks#building-the-files-object-dynamically).
{% endAside %}

- Load the Imagemin task by adding this line immediately before
  `grunt.registerTask(...)`:

<pre class="prettyprint">
<strong>grunt.loadNpmTasks('grunt-contrib-imagemin');</strong>
grunt.registerTask('default', [/* list plugins here */]);
</pre>


- Lastly, add Imagemin as the default Grunt task by replacing the `/* list plugins here */` comment with `'imagemin'`. That line should now look like this:

<pre class="prettyprint">
grunt.registerTask('default', <strong>['imagemin']</strong>);
</pre>

## ✔︎ Check-in

The complete `gruntfile.js` file should now look like this:

```javascript
const grunt = require('grunt')
grunt.initConfig({
  imagemin: {
    dynamic: {
      files: [{
        cwd: 'images/'
        expand: true,
        src: ['**/*.{png,jpg}'],
      }]
    }
  }
});
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);
```

## Customize your Imagemin Configuration

`imagemin-pngquant` is a plugin for specifying compression quality levels.
We've already added `imagemin-pngquant` to this project in the `package.json`
file so that you can use it to compress your PNGs. To use it, declare the plugin
and specify a compression quality level in your Gruntfile.


- Declare the `imagemin-pngquant` plugin by adding this line to the top of your
`gruntfile.js`:

<pre class="prettyprint">
<strong>const pngquant = require('imagemin-pngquant');</strong>
const grunt = require('grunt')
grunt.initConfig({
  ...
</pre>

- Add settings for compressing PNG images by adding an `options` property to the
  `imagemin` object. That `options` property should look like this:

<pre class="prettyprint">
grunt.initConfig({
  imagemin: {
    <strong>options: {</strong>
      <strong>use: [</strong>
        <strong>pngquant({quality: [0.5, 0.5]}),</strong>
      <strong>]</strong>
    <strong>},</strong>
    dynamic: {
  ...
</pre>

This code tells Imagemin to compress PNGs using the Pngquant plugin. The
`quality` field uses a `min` and `max` range of values to determine the
compression level—0 is the lowest and 1 is the highest. To force all images to
be compressed at 50% quality, pass `0.5` as both the min and max value.

## ✔︎ Check-in

Your `gruntfile.js` file should now look like this:

```javascript
const pngquant = require('imagemin-pngquant');
const grunt = require('grunt')
grunt.initConfig({
  imagemin: {
    options: {
      use: [
        pngquant({quality: [0.5, 0.5]}),
      ]
    },
    dynamic: {
      files: [{
        cwd: 'images/',
        expand: true,
        src: ['**/*.{png,jpg}'],
      }]
    }
  }
});
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);
```

But what about JPEGs? The project also has JPEG images, so you should specify how
they are compressed as well.

## Customize your Imagemin configuration (continued)

Use the `imagemin-mozjpeg` plugin, which has already been installed for you, to
compress JPEG images.

- Declare the `imagemin-mozjpeg` plugin by putting this line at the top your
  `gruntfile.js`.

<pre class="prettyprint">
<strong>const mozjpeg = require('imagemin-mozjpeg');</strong>
const pngquant = require('imagemin-pngquant');
const grunt = require('grunt');
</pre>

- Next, add `mozjpeg({quality: 50})` to the array in the `options` object.
  That array should now look like this:

<pre class="prettyprint">
grunt.initConfig({
  imagemin: {
    options: {
      use: [
        pngquant({quality: [0.5, 0.5]}),
        <strong>mozjpeg({quality: 50})</strong>
      ]
    },
    dynamic: {
</pre>

## ✔︎ Check-in

Your `gruntfile.js` file should now look like this:

```javascript
const mozjpeg = require('imagemin-mozjpeg');
const pngquant = require('imagemin-pngquant');
const grunt = require('grunt');
grunt.initConfig({
  imagemin: {
    options: {
      use: [
        pngquant({quality: [0.5, 0.5]}),
        mozjpeg({quality: 50})
      ]
    },
    dynamic: {
      files: [{
        cwd: 'images/',
        expand: true,
        src: ['**/*.{png,jpg}'],
      }]
    }
  }
});
grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);
```

## Run Grunt & verify results with Lighthouse

1. Click the **Tools** button.
1. Then click the **Console** button.
1. Run Grunt by typing the following command into the console:

<pre class="devsite-terminal devsite-click-to-copy">
grunt
</pre>

When Grunt completes you should see a message like this in console:

`Minified 6 images (saved 667 kB - 66.5%)`

Hooray! These results are much better.

Lastly, it's a good idea to use Lighthouse to verify the changes that you just
made. Lighthouse's "Efficiently encode images" performance audit will let you
know if the JPEG images on your page are optimally compressed.

{% Instruction 'preview' %}
- Run the Lighthouse performance audit (Lighthouse > Options > Performance) on
  the live version of your Glitch and verify that the "Efficiently encode
  images" audit was passed.

{% Img src="image/admin/TTrEG19zxZRSWNv2pRG4.png", alt="Passing 'Efficiently encode images' audit in Lighthouse", width="766", height="976", class="screenshot" %}

Success! You have used Imagemin to optimally compress the images on your page.
