svgo Documentation

SVG Optimizer for Node.js and CLI. ⚙️

22,626 stars JavaScript JavaScript 1 file · ~2,989 tokens #cli#hacktoberfest#javascript#minification#nodejs#optimization#svg#svgo
RAW Doc

File: README.md

SVGO [](https://npmjs.org/package/svgo) [](https://discord.gg/z8jX8NYxrE) [](https://svgo.dev/)

SVGO, short for SVG Optimizer, is a Node.js library and command-line application for optimizing SVG files.

Why?

SVG files, especially those exported from vector editors, usually contain a lot of redundant information. This includes editor metadata, comments, hidden elements, default or suboptimal values, and other stuff that can be safely removed or converted without impacting rendering.

Installation

You can install SVGO globally through npm, yarn, or pnpm. Alternatively, drop the global flag (global/-g) to use it in your Node.js project.

sh
# npm
npm install svgo

# yarn
yarn global add svgo

# pnpm
pnpm add svgo

Command-line usage

Process single files:

sh
svgo one.svg two.svg -o one.min.svg two.min.svg

Process a directory of files recursively with -r/--recursive and -f/--folder:

sh
svgo -rf path/to/directory_with_svgs -o path/to/output_directory

Help for advanced usage:

sh
svgo --help

Configuration

SVGO has a plugin architecture. You can read more about all plugins in Plugins | SVGO Documentation, and the default plugins in Preset Default | SVGO Documentation.

SVGO reads the configuration from svgo.config.mjs or the --config path/to/config.mjs command-line option. Some other parameters can be configured though command-line options too.

svgo.config.mjs

js
export default {
  multipass: false, // boolean
  datauri: 'base64', // 'base64'|'enc'|'unenc'
  js2svg: {
    indent: 4, // number
    pretty: false, // boolean
  },
  plugins: [
    'preset-default', // built-in plugins enabled by default
    'prefixIds', // enable built-in plugins by name

    // enable built-in plugins with an object to configure plugins
    {
      name: 'prefixIds',
      params: {
        prefix: 'uwu',
      },
    },
  ],
};

Default preset

Instead of configuring SVGO from scratch, you can tweak the default preset to suit your needs by configuring or disabling the respective plugin.

svgo.config.mjs

js
export default {
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // disable a default plugin
          cleanupIds: false,

          // customize the params of a default plugin
          inlineStyles: {
            onlyMatchedOnce: false,
          },
        },
      },
    },
  ],
};

You can find a list of the default plugins in the order they run in Preset Default | SVGO Documentation.

Custom plugins

You can also specify custom plugins:

svgo.config.mjs

js
import importedPlugin from './imported-plugin';

export default {
  plugins: [
    // plugin imported from another JavaScript file
    importedPlugin,

    // plugin defined inline
    {
      name: 'customPlugin',
      params: {
        paramName: 'paramValue',
      },
      fn: (ast, params, info) => {},
    },
  ],
};

API usage

SVGO provides a few low level utilities.

optimize

The core of SVGO is optimize function.

js
import { optimize } from 'svgo';

const result = optimize(svgString, {
  path: 'path-to.svg', // recommended
  multipass: true, // all other config fields are available here
});

const optimizedSvgString = result.data;

loadConfig

If you write a tool on top of SVGO you may want to resolve the svgo.config.mjs file.

js
import { loadConfig } from 'svgo';

const config = await loadConfig();

You can also specify a path and customize the current working directory.

js
const config = await loadConfig(configFile, cwd);

Donors

SheetJS LLC Fontello

This software is released under the terms of the MIT license.

Logo by André Castillo.


File: docs/02-usage/01-node.mdx


title: Node.js slug: 'node'

To minimally use SVGO in Node.js, ensure you've installed the dependency by following the instructions in Getting Started, then import the optimize function.

Here's a minimal example:

js
import { optimize } from 'svgo';

const svg = `
<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  viewBox="0 0 100 100">
  <text x="50" y="50" text-anchor="middle">•ᴗ•</text>
</svg>
`;

const { data } = optimize(svg);
console.log(data);
// <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50" y="50" text-anchor="middle">•ᴗ•</text></svg>

File: docs/02-usage/index.mdx


title: Usage

We officially support four interfaces for SVGO:

Community

Thanks to the community who have integrated, wrapped, or otherwise adapted SVGO to play well with other tools, and ultimately made SVGO more accessible for everyone.

This section showcases reputable projects that are stable and well maintained. Please check the project's website for more information on how to use it.

Integrations

Depending on your project stack, you may want to try one of these integrations to seamlessly incorporate SVGO into your workflow:

  • SVGR - Webpack loader that optimizes and transforms SVGs into React components.
  • grunt-svgmin - Grunt task to optimize SVGs.
  • postcss-svgo - PostCSS plugin that optimizes inline SVGs in CSS.
  • @figma-export - Node.js library to transforms Figma components into optimized SVGs.

Frontends

The community have developed many frontends for SVGO, and some even have additional features on top:

  • SVGOMG - Web application that wraps SVGO.
  • Oh My SVG - Linux desktop application that wraps SVGO.
  • SVG Gobbler - Browser extension for finding, optimizing, and exporting SVGs.

File: docs/04-plugins/addAttributesToSVGElement.mdx


title: addAttributesToSVGElement
svgo:
pluginId: addAttributesToSVGElement
parameters:
attributes:
default: null
attribute:


Adds attributes to the outer most <svg> element in the document. This is not an optimization and will increase the size of SVG documents.

:::danger

This plugin is only safe to use when a map of key/value pairs is passed. If you pass an array of keys to declare empty attributes, this will produce an malformed SVG that's only usable inline an HTML document.

:::


File: docs/04-plugins/addClassesToSVGElement.mdx


title: addClassesToSVGElement
svgo:
pluginId: addClassesToSVGElement
parameters:
classNames:
default: null
className:


Overrides the class attribute in the outer most <svg> element, omitting duplicates or null classes if found in your configuration.

:::caution

If there is no class attribute to begin with, it will be added. However, if the there were already classes assigned, these are removed and replaced with the classes configured in this plugin.

:::

If you have a standalone SVG, this is not an optimization and will increase the size of the SVG document. This plugin is only relevant when considering multiple SVGs that may be inlined a parent document.

By adding classes, if the parent document is aware, you can share styles across all inlined SVG elements.


File: docs/04-plugins/cleanupAttrs.mdx


title: cleanupAttrs
svgo:
pluginId: cleanupAttrs
parameters:
newlines:
type: boolean
default: true
trim:
type: boolean
default: true
spaces:
type: boolean
default: true


Removes redundant whitespaces from attribute values.

This will not modify the attribute keys, nor remove them if the value becomes empty after optimization.


File: docs/04-plugins/cleanupEnableBackground.mdx


title: cleanupEnableBackground svgo: pluginId: cleanupEnableBackground

Cleans up enable-background, unless the document uses <filter> elements.

Only cleans up attribute values and inline-styles, but does not affect stylesheets in <style> nodes.

This plugin will:

  • Drop enable-background when the width and height values match the width and height of the <svg> node.
  • Replace the value with new when the width and height values match the width and height of a <mask> or `` node.

:::info

Some browsers don't support enable-background, so it's best to avoid the attribute regardless.

:::


File: docs/04-plugins/cleanupIds.mdx


title: cleanupIds
svgo:
pluginId: cleanupIds
parameters:
remove:
default: true
minify:
default: true
preserve:
default: []
preservePrefixes:
default: []
force:
default: false


Removes unused IDs, and minifies IDs that are referenced by other elements.

By default, we back off from removing and minifying IDs if a <script> or <style> element is present in the document. You can bypass this behavior by setting the force parameter to true.

:::info

Between v2 and v3, the plugin was renamed from cleanupIDs to cleanupIds, if you've recently migrated and having issues, please double-check the capitalization!

:::

:::caution

This plugin has been known to cause problems when inlining multiple SVGs in the same parent document. Due to the predictable algorithm used to minify IDs, separate documents that are run though SVGO may end up with clashing IDs.

You can work around this by enabling the prefixIds plugin. Alternatively, you can set the minify parameter to false, however this will not resolve the issue if your SVGs already had clashing IDs to start with.

See facebook/docusaurus#8297 for more context.

:::


File: docs/04-plugins/cleanupListOfValues.mdx


title: cleanupListOfValues
svgo:
pluginId: cleanupListOfValues
parameters:
floatPrecision:
default: 3
leadingZero:
default: true
defaultPx:
default: true
convertToPx:
default: true


Rounds numeric values in attributes, such as those found in viewBox, enable-background, and points.