3.2.0 • Published 4 months ago

svgo v3.2.0

Weekly downloads
10,149,049
License
MIT
Repository
github
Last release
4 months ago

SVGO npm version Discord

SVG Optimizer is a Node.js-based tool for optimizing SVG vector graphics files.

Why?

SVG files, especially those exported from various editors, usually contain a lot of redundant and useless information. This can include editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting the SVG rendering result.

Installation

# Via npm
npm -g install svgo
# Via yarn
yarn global add svgo

CLI usage

# Processing single files:
svgo one.svg two.svg -o one.min.svg two.min.svg
# Processing directory of svg files, recursively using `-f`, `--folder` :
svgo -f ./path/to/folder/with/svg/files -o ./path/to/folder/with/svg/output
# Help for advanced usage
svgo --help

Configuration

SVGO has a plugin-based architecture, separate plugins allows various xml svg optimizations. See built-in plugins. SVGO automatically loads configuration from svgo.config.js or from --config ./path/myconfig.js. Some general options can be configured via CLI.

// svgo.config.js
module.exports = {
  multipass: true, // boolean. false by default
  datauri: 'enc', // 'base64' (default), 'enc' or 'unenc'.
  js2svg: {
    indent: 2, // string with spaces or number of spaces. 4 by default
    pretty: true, // boolean, false by default
  },
  plugins: [
    // set of built-in plugins enabled by default
    'preset-default',

    // enable built-in plugins by name
    'prefixIds',

    // or by expanded notation which allows to configure plugin
    {
      name: 'sortAttrs',
      params: {
        xmlnsOrder: 'alphabetical',
      },
    },
  ],
};

Default preset

When extending default configuration specify preset-default plugin to enable optimisations. Each plugin of default preset can be disabled or configured with "overrides" param.

module.exports = {
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // customize default plugin options
          inlineStyles: {
            onlyMatchedOnce: false,
          },

          // or disable plugins
          removeDoctype: false,
        },
      },
    },
  ],
};

Default preset includes the following list of plugins:

  • removeDoctype
  • removeXMLProcInst
  • removeComments
  • removeMetadata
  • removeEditorsNSData
  • cleanupAttrs
  • mergeStyles
  • inlineStyles
  • minifyStyles
  • cleanupIds
  • removeUselessDefs
  • cleanupNumericValues
  • convertColors
  • removeUnknownsAndDefaults
  • removeNonInheritableGroupAttrs
  • removeUselessStrokeAndFill
  • removeViewBox
  • cleanupEnableBackground
  • removeHiddenElems
  • removeEmptyText
  • convertShapeToPath
  • convertEllipseToCircle
  • moveElemsAttrsToGroup
  • moveGroupAttrsToElems
  • collapseGroups
  • convertPathData
  • convertTransform
  • removeEmptyAttrs
  • removeEmptyContainers
  • mergePaths
  • removeUnusedNS
  • sortDefsChildren
  • removeTitle
  • removeDesc

Custom plugin

It's also possible to specify a custom plugin:

const anotherCustomPlugin = require('./another-custom-plugin.js');
module.exports = {
  plugins: [
    {
      name: 'customPluginName',
      params: {
        optionName: 'optionValue',
      },
      fn: (ast, params, info) => {},
    },
    anotherCustomPlugin,
  ],
};

API usage

SVGO provides a few low level utilities.

optimize

The core of SVGO is optimize function.

const { optimize } = require('svgo');
const result = optimize(svgString, {
  // optional but recommended field
  path: 'path-to.svg',
  // all config fields are also available here
  multipass: true,
});
const optimizedSvgString = result.data;

loadConfig

If you write a tool on top of SVGO you might need a way to load SVGO config.

const { loadConfig } = require('svgo');
const config = await loadConfig();

// you can also specify a relative or absolute path and customize the current working directory
const config = await loadConfig(configFile, cwd);

Built-in plugins

PluginDescriptionDefault
cleanupAttrscleanup attributes from newlines, trailing, and repeating spacesenabled
mergeStylesmerge multiple style elements into oneenabled
inlineStylesmove and merge styles from <style> elements to element style attributesenabled
removeDoctyperemove doctype declarationenabled
removeXMLProcInstremove XML processing instructionsenabled
removeCommentsremove commentsenabled
removeMetadataremove <metadata>enabled
removeTitleremove <title>enabled
removeDescremove <desc>enabled
removeUselessDefsremove elements of <defs> without idenabled
removeXMLNSremoves the xmlns attribute (for inline SVG)disabled
removeEditorsNSDataremove editors namespaces, elements, and attributesenabled
removeEmptyAttrsremove empty attributesenabled
removeHiddenElemsremove hidden elementsenabled
removeEmptyTextremove empty Text elementsenabled
removeEmptyContainersremove empty Container elementsenabled
removeViewBoxremove viewBox attribute when possibleenabled
cleanupEnableBackgroundremove or cleanup enable-background attribute when possibleenabled
minifyStylesminify <style> elements content with CSSOenabled
convertStyleToAttrsconvert styles into attributesdisabled
convertColorsconvert colors (from rgb() to #rrggbb, from #rrggbb to #rgb)enabled
convertPathDataconvert Path data to relative or absolute (whichever is shorter), convert one segment to another, trim useless delimiters, smart rounding, and much moreenabled
convertTransformcollapse multiple transforms into one, convert matrices to the short aliases, and much moreenabled
removeUnknownsAndDefaultsremove unknown elements content and attributes, remove attributes with default valuesenabled
removeNonInheritableGroupAttrsremove non-inheritable group's "presentation" attributesenabled
removeUselessStrokeAndFillremove useless stroke and fill attributesenabled
removeUnusedNSremove unused namespaces declarationenabled
prefixIdsprefix IDs and classes with the SVG filename or an arbitrary stringdisabled
cleanupIdsremove unused and minify used IDsenabled
cleanupNumericValuesround numeric values to the fixed precision, remove default px unitsenabled
cleanupListOfValuesround numeric values in attributes that take a list of numbers (like viewBox or enable-background)disabled
moveElemsAttrsToGroupmove elements' attributes to their enclosing groupenabled
moveGroupAttrsToElemsmove some group attributes to the contained elementsenabled
collapseGroupscollapse useless groupsenabled
removeRasterImagesremove raster imagesdisabled
mergePathsmerge multiple Paths into oneenabled
convertShapeToPathconvert some basic shapes to <path>enabled
convertEllipseToCircleconvert non-eccentric <ellipse> to <circle>enabled
sortAttrssort element attributes for epic readabilityenabled
sortDefsChildrensort children of <defs> in order to improve compressionenabled
removeDimensionsremove width/height and add viewBox if it's missing (opposite to removeViewBox, disable it first)disabled
removeAttrsremove attributes by patterndisabled
removeAttributesBySelectorremoves attributes of elements that match a CSS selectordisabled
removeElementsByAttrremove arbitrary elements by ID or classNamedisabled
addClassesToSVGElementadd classnames to an outer <svg> elementdisabled
addAttributesToSVGElementadds attributes to an outer <svg> elementdisabled
removeOffCanvasPathsremoves elements that are drawn outside of the viewboxdisabled
removeStyleElementremove <style> elementsdisabled
removeScriptElementremove <script> elementsdisabled
reusePathsFind duplicated elements and replace them with linksdisabled

Other Ways to Use SVGO

Donators

SheetJS LLCFontello

License and Copyright

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

Logo by André Castillo.

postcss-svgo@svgr/plugin-svgovite-plugin-mini-svg@alexghi/reiconsfresh-compressee.web.icons@adapt-design-system/core@cc-design/cestc-vue-scripts@parksunghyun0112/react-spring-bottom-sheet-updated@itsi/base@ray.js/cli@knapsack/rollup-config-starter@realness.online/web-workersvuedragdropuploadimages@inevix/grunt-webfont@dmytrohusiev/fork-babel-plugin-inline-react-svg@bearjam/gatsby-transformer-svgo-inline@tenjo/wapp@s-isabella/scripts-frontend@isi-gach/babel-plugin-inline-react-svgbabel-plugin-inline-react-svg-folkdexdotevelinaproject-name-heresop-cdm@cashremit/cr-streamline-iconsasqi-md2html@aasaam/pwa-tools@mygooder/react-scripts@supl.biz_tech/import-svg@supl.biz_tech/svg-componentsgrunt-webfont-patchedcloud-archive-s3grunt-webfontixix-grunt-webfontwebj2ee-iconsbb-chat@bliss-design-system/iconsetnpm-test-this-publishhydra-generator@fundefund/funde_ck@ng-easy/semantic-release-angular@pboi20/svgbundle@doggoapp/doggo-mobile-components-tseslint-plugin-svgo@codewitchbella/scripts-frontendtestpkg-new@dalitaavanesian/reiconsgql_din_modmetalsmith-minify-svghyperfilerafryxiconsgreencheap-uikit@ithinkdt-cloud/vite-svg-component@korzhyk/preact-svg-core@korzhyk/react-svg-coregatsby-plugin-sharp-esdr-svg-composer@olivervorasai/slider@rdfkit/generate-iconlibreact-app-rewired-upstreamped@ads-medienmanufaktur/easy-sprite@eaze/eaze-web-scriptsflymopet-vuecogoportutils@alexstrnik-figma-extractor/svgo-optimizefigma-portal@nuxtjs-alt/svg-spriteresponsiv-image-handlerunblock-block-save-variables@bncfe/cli@twigger/svgo@sdf-1/svgo@cestc-design/cestc-vue-scripts@twbs/svg-sprite@saaspe/components@h1-card/h1-fe-icons@knapsack/toby@knapsack/app-ui@wakeful-cloud/penpot-uploaderqc-webpack-svgstore-pluginquad-webpack-svgstore-pluginbackfr-builderexpand-react-bridgepico-svgsklif-ui-kitsklif-apihydra-svg-js@everything-registry/sub-chunk-2859@pxwlab/sprite-cli@pxwlab/katana-builder@toolx/tool-svg@cli107/figma-export@314oner_npm/universal-components-librarypxw-sprite-clireact-native-credit-card-pkgp149-tabletest-popupsplugin-theme-componentsklif-ui
3.2.0

4 months ago

3.1.0

4 months ago

3.0.4

5 months ago

3.0.3

5 months ago

3.0.5

5 months ago

3.0.2

1 year ago

3.0.1

1 year ago

3.0.0

1 year ago

2.8.0

2 years ago

2.7.0

3 years ago

2.6.1

3 years ago

2.6.0

3 years ago

2.5.0

3 years ago

2.4.0

3 years ago

2.3.1

3 years ago

2.3.0

3 years ago

2.2.2

3 years ago

2.2.1

3 years ago

2.2.0

3 years ago

2.1.0

3 years ago

2.0.3

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.3.2

4 years ago

1.3.1

4 years ago

1.3.0

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.1

6 years ago

1.1.0

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.7.2

7 years ago

0.7.1

8 years ago

0.7.0

8 years ago

0.6.6

8 years ago

0.6.5

8 years ago

0.6.4

8 years ago

0.6.3

8 years ago

0.6.2

8 years ago

0.6.1

8 years ago

0.6.0

8 years ago

0.5.6

9 years ago

0.5.5

9 years ago

0.5.4

9 years ago

0.5.3

9 years ago

0.5.2

9 years ago

0.5.1

9 years ago

0.5.0

9 years ago

0.4.5

10 years ago

0.4.4

10 years ago

0.4.3

10 years ago

0.4.2

10 years ago

0.4.1

10 years ago

0.4.0

10 years ago

0.3.7

11 years ago

0.3.6

11 years ago

0.3.5

11 years ago

0.3.4

11 years ago

0.3.3

11 years ago

0.3.2

11 years ago

0.3.1

11 years ago

0.3.0

11 years ago

0.2.4

11 years ago

0.2.3

11 years ago

0.2.2

11 years ago

0.2.1

11 years ago

0.2.0

11 years ago

0.1.9-1

11 years ago

0.1.9

11 years ago

0.1.8

11 years ago

0.1.7

11 years ago

0.1.6

11 years ago

0.1.5

11 years ago

0.1.4

11 years ago

0.1.3

11 years ago

0.1.2

11 years ago

0.1.1

11 years ago

0.1.0

11 years ago

0.0.9-1

11 years ago

0.0.9

11 years ago

0.0.8-1

12 years ago

0.0.8

12 years ago

0.0.7-1

12 years ago

0.0.7

12 years ago

0.0.6

12 years ago

0.0.5-1

12 years ago

0.0.5

12 years ago

0.0.4

12 years ago

0.0.3

12 years ago

0.0.2

12 years ago

0.0.1-3

12 years ago

0.0.1-2

12 years ago

0.0.1

12 years ago