How to Minify and Optimize SVG Code Using SVGO

Scalable Vector Graphics (SVGs) often contain redundant metadata, editor comments, hidden elements, and excessive precision points that inflate file sizes. SVGO (SVG Optimizer) is a Node.js-based command-line tool and library designed to strip away this unnecessary data without affecting the visual rendering of the vector. This guide covers how to install SVGO, optimize individual or batched SVG files via the Command Line Interface (CLI), customize plugins via configuration files, and automate the optimization process in modern web development workflows.

What is SVGO?

SVGO operates by parsing SVG files into an Abstract Syntax Tree (AST), applying a series of plugin-driven transformations, and serializing the tree back into clean, minified SVG markup. It removes doctype declarations, XML namespaces, metadata from design software (such as Adobe Illustrator, Figma, or Inkscape), unused elements, and rounds floating-point numbers to reduce file payload significantly.

Installing SVGO

SVGO can be run on-demand using npx or installed globally or locally within a Node.js project.

Run on-demand (No installation required)

npx svgo input.svg -o output.svg

Global Installation

npm install -g svgo

Local Project Installation

npm install --save-dev svgo

Basic CLI Usage

Once installed, SVGO can process individual files, entire directories, or standard input streams.

Optimize a Single File

To optimize an input file and save it to a new location:

svgo input.svg -o output.svg

To overwrite the original file with the optimized version:

svgo input.svg

Optimize Multiple Files and Folders

To process all SVG files in a specific directory and output them to a separate folder:

svgo -f ./src/icons -o ./dist/icons

To optimize all SVGs in a folder in place:

svgo -f ./src/icons

Multipass Optimization

Passing the --multipass flag runs optimizations repeatedly until no further byte reductions can be made:

svgo input.svg --multipass

Customizing SVGO Configuration

SVGO is highly configurable via a svgo.config.js or svgo.config.mjs file placed in the root of your project. This configuration allows you to enable, disable, and adjust specific plugins.

Example svgo.config.js

module.exports = {
  multipass: true, // Run optimizations multiple times
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // Prevent removing the viewBox attribute to maintain responsiveness
          removeViewBox: false,
          // Adjust float precision for coordinates
          cleanupNumericValues: {
            floatPrecision: 2,
          },
        },
      },
    },
    // Custom plugins outside default preset
    'removeDimensions', // Removes width/height attributes in favor of viewBox
    'sortAttrs',        // Sorts element attributes for better gzip compression
  ],
};

Key Configuration Best Practices

  1. Retain the viewBox Attribute: When integrating SVGs into responsive web layouts, preserve viewBox by setting removeViewBox: false. Removing viewBox while discarding width and height can break image scaling.
  2. Tune Precision: Setting floatPrecision between 1 and 3 drastically cuts coordinate string length with negligible loss of visual fidelity.
  3. Remove Explicit Dimensions: Enabling removeDimensions strips width and height, allowing the SVG size to be entirely controlled by CSS.

Automating SVGO in Web Development

To prevent unoptimized SVGs from entering production, SVGO can be integrated into build scripts and automated pipelines:

NPM Script Integration

Add a minification script to your package.json:

{
  "scripts": {
    "optimize:svg": "svgo -f ./assets/raw-svgs -o ./assets/optimized-svgs --multipass"
  }
}

Webpack Integration

When using Webpack, use image-minimizer-webpack-plugin with SVGO to optimize assets automatically during the build step:

const ImageMinimizerPlugin = require('image-minimizer-webpack-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/,
        type: 'asset/resource',
      },
    ],
  },
  optimization: {
    minimizer: [
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.svgoMinify,
          options: {
            encodeOptions: {
              multipass: true,
              plugins: ['preset-default'],
            },
          },
        },
      }),
    ],
  },
};

Vite Integration

In Vite-based projects, use dedicated plugins like vite-plugin-svgo to optimize vector graphics automatically during asset bundling.