35: Optimizing SVG with Tools

(Updated on )

We talked about optimizing SVG by hand already. Making choices manually about detail and what kinds of things can be combined or removed. In this screencast we’ll look at optimizing SVG with tools. Tools that can reduce the file size of SVG without (hopefully) changing the look of it at all. Things that are perfect for automation. Like:

  • Removing whitespace
  • Reducing the precision of numbers
  • Removing metadata cruft

The most popular tool for that is SVGO, a node-based command tool for optimzing SVG this way. It has a GUI version, so you can just drag-and-drop as well like something like ImageOptim. (In the video, we needed this to unzip it.)

We also looked at Peter Collingridge’s SVG optimization tools, which were neat in that you can pick and choose what rules you wanted to apply then see the results and file size.

Optimizing by hand might be OK in some cases where you’re working with a small number of files and on occasion. But if you’re working with SVG a lot, like you’re building out an icon system, it’s probably best to incorporate the tool into the build system.

We’ve looked at Grunt here before, so let’s imagine a system that:

  1. Optimizes SVG anytime an SVG file is added or is changed in our project
  2. Then builds them all together into a defs.svg block

You’d do the optimization first and build out a folder full of those (so they can be inspected one by one if needed), then build them together. Here’s what that Gruntfile would look like using grunt-svgmin and grunt-svgstore:

module.exports = function(grunt) {

  grunt.initConfig({

    svgmin: {
      options: {
        plugins: [
          {
            removeViewBox: true
          }, {
            removeUselessStrokeAndFill: false
          }
        ]
      },
      dist: {
        files: [{
          expand: true,
          cwd: "svg/",
          src: ['*.svg'],
          dest: 'svgo/'
        }]
      }
    },

    svgstore: {
      options: {
        formatting : {
          indent_size : 2
        }
      },
        default: {
          files: {
          'includes/defs.svg': ['svgo/*.svg'],
        }
      }
    }

  });

  grunt.loadNpmTasks('grunt-svgstore');
  grunt.loadNpmTasks('grunt-svgmin');

  grunt.registerTask('default', ['svgmin', 'svgstore']);

};

I’ll drop in the SVG image we played with (from Freepik) and a zip of the Grunt project as downloads.