CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-svgo

Node.js library and command-line application for optimizing SVG vector graphics files

Pending
Overview
Eval results
Files

plugins.mddocs/

Plugin System

Comprehensive plugin architecture with 50+ built-in plugins for SVG optimization, organized into categories like cleanup, removal, conversion, and styling operations.

Capabilities

Built-in Plugins

Access to all built-in SVGO plugins.

/**
 * Array of all built-in SVGO plugins
 */
const builtinPlugins: ReadonlyArray<BuiltinPluginOrPreset<string, any>>;

interface BuiltinPluginOrPreset<Name extends string, Params> {
  /** Name of the plugin, also known as the plugin ID */
  name: Name;
  /** Optional description of what the plugin does */
  description?: string;
  /** Plugin implementation function */
  fn: Plugin<Params>;
  /** If the plugin is itself a preset that invokes other plugins */
  isPreset?: true;
  /** 
   * If the plugin is a preset that invokes other plugins, this returns an
   * array of the plugins in the preset in the order that they are invoked
   */
  plugins?: ReadonlyArray<BuiltinPlugin<string, Object>>;
}

interface Plugin<P = any> {
  (root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;
}

Usage Examples:

import { builtinPlugins } from "svgo";

// List all available plugins
console.log(builtinPlugins.map(plugin => plugin.name));

// Find a specific plugin
const removeComments = builtinPlugins.find(p => p.name === 'removeComments');
console.log(removeComments.description);

// Check if a plugin is a preset
const presetDefault = builtinPlugins.find(p => p.name === 'preset-default');
if (presetDefault.isPreset) {
  console.log('Preset includes:', presetDefault.plugins.map(p => p.name));
}

Plugin Configuration

Configure individual plugins with custom parameters.

type PluginConfig = 
  | string  // Plugin name for builtin plugins with default params
  | {
      name: string;
      params?: any;
      fn?: Plugin;  // Custom plugin function
    }
  | CustomPlugin;

interface CustomPlugin<T = any> {
  name: string;
  fn: Plugin<T>;
  params?: T;
}

Default Preset

The default plugin preset that runs when no plugins are specified.

/**
 * Default preset configuration with 35 optimization plugins
 */
interface PresetDefaultConfig {
  /** Global floating point precision */
  floatPrecision?: number;
  /** Override settings for individual plugins */
  overrides?: {
    [PluginName in DefaultPluginNames]?: PluginParams[PluginName] | false;
  };
}

Default Preset Plugins (in execution order):

  1. removeDoctype - Remove DOCTYPE declarations
  2. removeXMLProcInst - Remove XML processing instructions
  3. removeComments - Remove XML comments
  4. removeDeprecatedAttrs - Remove deprecated attributes
  5. removeMetadata - Remove <metadata> elements
  6. removeEditorsNSData - Remove editor namespace data
  7. cleanupAttrs - Clean up attributes
  8. mergeStyles - Merge multiple <style> elements
  9. inlineStyles - Inline CSS styles
  10. minifyStyles - Minify CSS in <style> elements
  11. cleanupIds - Clean up IDs
  12. removeUselessDefs - Remove useless <defs> elements
  13. cleanupNumericValues - Clean up numeric values
  14. convertColors - Convert colors to shorter formats
  15. removeUnknownsAndDefaults - Remove unknown and default values
  16. removeNonInheritableGroupAttrs - Remove non-inheritable group attributes
  17. removeUselessStrokeAndFill - Remove useless stroke and fill
  18. cleanupEnableBackground - Clean up enable-background
  19. removeHiddenElems - Remove hidden elements
  20. removeEmptyText - Remove empty text elements
  21. convertShapeToPath - Convert shapes to paths
  22. convertEllipseToCircle - Convert ellipses to circles
  23. moveElemsAttrsToGroup - Move element attributes to group
  24. moveGroupAttrsToElems - Move group attributes to elements
  25. collapseGroups - Collapse groups
  26. convertPathData - Convert path data
  27. convertTransform - Convert transforms
  28. removeEmptyAttrs - Remove empty attributes
  29. removeEmptyContainers - Remove empty containers
  30. mergePaths - Merge paths
  31. removeUnusedNS - Remove unused namespaces
  32. sortAttrs - Sort attributes
  33. sortDefsChildren - Sort defs children
  34. removeDesc - Remove description elements

Plugin Categories

Cleanup Plugins

Plugins that clean and normalize SVG content.

// Cleanup attribute values and formatting
'cleanupAttrs'           // Clean up attributes
'cleanupIds'             // Clean up IDs  
'cleanupNumericValues'   // Clean up numeric values
'cleanupEnableBackground' // Clean up enable-background
'cleanupListOfValues'    // Clean up list values

Examples:

// cleanupAttrs - removes unnecessary whitespace and normalizes values
{
  name: 'cleanupAttrs',
  params: {
    newlines: true,    // Remove newlines
    trim: true,        // Trim whitespace
    spaces: true       // Normalize spaces
  }
}

// cleanupIds - optimizes ID values
{
  name: 'cleanupIds',
  params: {
    remove: true,      // Remove unused IDs
    minify: true,      // Minify ID names
    preserve: ['keep-this-id']  // IDs to preserve
  }
}

// cleanupNumericValues - formats numeric values
{
  name: 'cleanupNumericValues',
  params: {
    floatPrecision: 2,  // Decimal places
    leadingZero: true,  // Remove leading zeros
    defaultPx: true     // Remove default px units
  }
}

Removal Plugins

Plugins that remove unnecessary SVG content.

// Document structure removal
'removeDoctype'          // Remove DOCTYPE
'removeXMLProcInst'      // Remove XML processing instructions
'removeComments'         // Remove comments
'removeMetadata'         // Remove metadata

// Content removal
'removeDesc'             // Remove description elements
'removeTitle'            // Remove title elements
'removeEmptyAttrs'       // Remove empty attributes
'removeEmptyText'        // Remove empty text
'removeEmptyContainers'  // Remove empty containers
'removeHiddenElems'      // Remove hidden elements

// Attribute removal
'removeDeprecatedAttrs'  // Remove deprecated attributes
'removeAttrs'            // Remove specific attributes
'removeElementsByAttr'   // Remove elements by attribute
'removeAttributesBySelector' // Remove attributes by selector

// Advanced removal
'removeUselessDefs'      // Remove useless definitions
'removeUselessStrokeAndFill' // Remove useless stroke and fill
'removeUnusedNS'         // Remove unused namespaces
'removeUnknownsAndDefaults' // Remove unknowns and defaults
'removeNonInheritableGroupAttrs' // Remove non-inheritable group attributes
'removeEditorsNSData'    // Remove editor namespace data
'removeRasterImages'     // Remove raster images
'removeScripts'          // Remove scripts
'removeStyleElement'     // Remove style elements
'removeViewBox'          // Remove viewBox
'removeXlink'            // Remove XLink references
'removeXMLNS'            // Remove XML namespace
'removeDimensions'       // Remove dimensions
'removeOffCanvasPaths'   // Remove off-canvas paths

Examples:

// removeAttrs - remove specific attributes
{
  name: 'removeAttrs',
  params: {
    attrs: ['data-*', 'class', 'style']
  }
}

// removeElementsByAttr - remove elements with specific attributes
{
  name: 'removeElementsByAttr',
  params: {
    id: ['unwanted-id'],
    class: ['remove-this']
  }
}

// removeHiddenElems - remove invisible elements
{
  name: 'removeHiddenElems',
  params: {
    isHidden: true,        // Remove display:none elements
    displayNone: true,     // Remove opacity:0 elements
    opacity0: true         // Remove visibility:hidden elements
  }
}

Conversion Plugins

Plugins that convert SVG elements to more optimal formats.

'convertColors'          // Convert colors to shorter formats
'convertEllipseToCircle' // Convert ellipses to circles
'convertShapeToPath'     // Convert shapes to paths
'convertPathData'        // Convert path data
'convertTransform'       // Convert transforms
'convertStyleToAttrs'    // Convert styles to attributes
'convertOneStopGradients' // Convert one-stop gradients

Examples:

// convertColors - optimize color values
{
  name: 'convertColors',
  params: {
    currentColor: true,   // Convert to currentColor
    names2hex: true,      // Convert color names to hex
    rgb2hex: true,        // Convert RGB to hex
    shorthex: true,       // Use short hex when possible
    shortname: true       // Use short color names
  }
}

// convertPathData - optimize path data
{
  name: 'convertPathData',
  params: {
    applyTransforms: true,      // Apply transforms to paths
    applyTransformsStroked: true, // Apply to stroked paths
    makeArcs: {
      threshold: 2.5,           // Arc conversion threshold
      tolerance: 0.5            // Arc tolerance
    },
    straightCurves: true,       // Convert curves to lines
    lineShorthands: true,       // Use line shorthands
    curveSmoothShorthands: true, // Use curve shorthands
    floatPrecision: 3,          // Float precision
    transformPrecision: 5,      // Transform precision
    removeUseless: true,        // Remove useless commands
    collapseRepeated: true,     // Collapse repeated commands
    utilizeAbsolute: true,      // Use absolute commands when shorter
    leadingZero: true,          // Remove leading zeros
    negativeExtraSpace: true    // Remove extra spaces around negatives
  }
}

Style Plugins

Plugins that handle CSS styles and styling attributes.

'mergeStyles'    // Merge multiple style elements
'inlineStyles'   // Inline CSS styles
'minifyStyles'   // Minify CSS styles

Examples:

// inlineStyles - inline CSS styles as attributes
{
  name: 'inlineStyles',
  params: {
    onlyMatchedOnce: true,    // Only inline styles used once
    removeMatchedSelectors: true, // Remove selectors after inlining
    useMqs: ['', 'screen'],   // Media queries to consider
    usePseudos: ['']          // Pseudo-classes to consider
  }
}

// minifyStyles - minify CSS content
{
  name: 'minifyStyles',
  params: {
    restructure: true,        // Restructure CSS
    forceMediaMerge: false,   // Force media query merging
    comments: false           // Remove comments
  }
}

Path Plugins

Plugins specifically for path manipulation.

'mergePaths'     // Merge multiple paths
'reusePaths'     // Reuse identical paths

Organization Plugins

Plugins that reorganize SVG structure.

'moveElemsAttrsToGroup'  // Move element attributes to group
'moveGroupAttrsToElems'  // Move group attributes to elements
'collapseGroups'         // Collapse unnecessary groups
'sortAttrs'              // Sort attributes
'sortDefsChildren'       // Sort defs children

Examples:

// sortAttrs - sort attributes alphabetically
{
  name: 'sortAttrs',
  params: {
    xmlnsOrder: 'alphabetical'  // or 'front'
  }
}

// collapseGroups - remove unnecessary groups
{
  name: 'collapseGroups',
  params: {
    collapseOther: true    // Collapse other containers too
  }
}

Enhancement Plugins

Plugins that add content to SVGs.

'addAttributesToSVGElement' // Add attributes to SVG element
'addClassesToSVGElement'    // Add classes to SVG element
'prefixIds'                 // Prefix IDs

Examples:

// addClassesToSVGElement - add CSS classes to root SVG
{
  name: 'addClassesToSVGElement',
  params: {
    classNames: ['optimized', 'icon']
  }
}

// prefixIds - add prefix to all IDs
{
  name: 'prefixIds',
  params: {
    prefix: 'icon-',
    delim: ''  // Delimiter between prefix and ID
  }
}

Custom Plugins

Create custom optimization plugins.

interface CustomPlugin<T = any> {
  name: string;
  fn: Plugin<T>;
  params?: T;
}

interface Plugin<P = any> {
  (root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;
}

interface PluginInfo {
  /** File path if available */
  path?: string;
  /** Current multipass iteration count */
  multipassCount: number;
}

interface Visitor {
  element?: VisitorNode<XastElement>;
  text?: VisitorNode<XastText>;
  comment?: VisitorNode<XastComment>;
  // ... other node types
}

interface VisitorNode<Node> {
  enter?: (node: Node, parentNode: XastParent) => void | symbol;
  exit?: (node: Node, parentNode: XastParent) => void;
}

Custom Plugin Examples:

// Custom plugin to remove specific elements
const removeCustomElements = {
  name: 'removeCustomElements',
  fn: (root, params) => {
    return {
      element: {
        enter(node, parent) {
          if (params.elements.includes(node.name)) {
            // Remove this element
            const index = parent.children.indexOf(node);
            parent.children.splice(index, 1);
          }
        }
      }
    };
  },
  params: {
    elements: ['unwanted-element', 'custom-tag']
  }
};

// Custom plugin to modify attributes
const modifyAttributes = {
  name: 'modifyAttributes',
  fn: (root, params) => {
    return {
      element: {
        enter(node) {
          if (node.name === 'rect') {
            // Round all numeric attributes
            Object.keys(node.attributes).forEach(attr => {
              const value = parseFloat(node.attributes[attr]);
              if (!isNaN(value)) {
                node.attributes[attr] = Math.round(value).toString();
              }
            });
          }
        }
      }
    };
  }
};

// Use custom plugins
import { optimize } from "svgo";

const result = optimize(svgString, {
  plugins: [
    'preset-default',
    removeCustomElements,
    modifyAttributes
  ]
});

Install with Tessl CLI

npx tessl i tessl/npm-svgo

docs

ast-manipulation.md

cli.md

configuration.md

core-optimization.md

data-uri.md

index.md

plugins.md

utility-functions.md

tile.json