Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

Up and Running with SVG

An SVG primer for everyone. Created by Mijingo.

Optimizing SVG with Grunt

Over in the SVG Performance section I mentioned the SVGO command line utility and that there is a Grunt plugin available. Here’s how to use the Grunt plugin to optimize SVG images automatically as part of your web devleopment workflow.

The SVGO utility as a Grunt plugin is called grunt-svgmin.

Installing grunt-svgmin

Before we can use SVGO in our Gruntfile.js as task, we need to first install it. Just like we did in the JavaScript Task Runners course, we need to run npm install to install the plugin.

npm install grunt-svgmin --save-dev

We use --save-dev so the plugin will be saved in our package.json file and set as a dependency for our project.

With the plugin installed we can know define our task in the Gruntfile.js file. Here’s what it’ll look like:

svgmin: {
    options: {
        plugins: {
            removeViewBox: false
        }
    },
    dist: {
        files: {
            'images/svg/atom.svg' : 'src/svg/atom.svg'
        }
    }
}

This task will be nestled somewhere in your Gruntfile.js file.

This Grunt implementation of SVGO uses the same plugins as normal SVGO. Refer to the full list of SVGO plugins to see what you can do in your task. The plugins are enabled by default so you’ll have to disable anything that you don’t want. This will be necessary if you find that the resulting SVG is altering too much from the original in terms of apperance. In this example we are disabling removeViewBox, which is an optimization that SVGO can do for you.

I set up a target called dist where I’m targeting a specific image. The destination image comes first. It will be saved in the directory images/svg.

We can’t forget to load the plugin, too, so let’s do that at the bottom of the Gruntfile.js file.

grunt.loadNpmTasks('grunt-svgmin');

Okay, so let’s run this task to see it work.

grunt svgmin

You should get a result similar to this:

Running "svgmin:dist" (svgmin) task
✓ src/svg/atom.svg (saved 53 B 11%)
Total saved: 53 B

Done, without errors.

Looking at the SVG I converted, I shaved about a bit off the image (it was pretty small to begin with) but every byte counts! You’ll see much more savings on larger, more complex images.

Roll the Tape

Here’s a video walking you through the entire thing:

This tutorial is an extra feature of this site. If you want to learn everything you need to know to get started with SVG, please check out the course I created (use the big button below to learn more).

Ready to learn more?

Get the Full Video Course