Node.js library and command-line application for optimizing SVG vector graphics files
—
Comprehensive plugin architecture with 50+ built-in plugins for SVG optimization, organized into categories like cleanup, removal, conversion, and styling operations.
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));
}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;
}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):
removeDoctype - Remove DOCTYPE declarationsremoveXMLProcInst - Remove XML processing instructionsremoveComments - Remove XML commentsremoveDeprecatedAttrs - Remove deprecated attributesremoveMetadata - Remove <metadata> elementsremoveEditorsNSData - Remove editor namespace datacleanupAttrs - Clean up attributesmergeStyles - Merge multiple <style> elementsinlineStyles - Inline CSS stylesminifyStyles - Minify CSS in <style> elementscleanupIds - Clean up IDsremoveUselessDefs - Remove useless <defs> elementscleanupNumericValues - Clean up numeric valuesconvertColors - Convert colors to shorter formatsremoveUnknownsAndDefaults - Remove unknown and default valuesremoveNonInheritableGroupAttrs - Remove non-inheritable group attributesremoveUselessStrokeAndFill - Remove useless stroke and fillcleanupEnableBackground - Clean up enable-backgroundremoveHiddenElems - Remove hidden elementsremoveEmptyText - Remove empty text elementsconvertShapeToPath - Convert shapes to pathsconvertEllipseToCircle - Convert ellipses to circlesmoveElemsAttrsToGroup - Move element attributes to groupmoveGroupAttrsToElems - Move group attributes to elementscollapseGroups - Collapse groupsconvertPathData - Convert path dataconvertTransform - Convert transformsremoveEmptyAttrs - Remove empty attributesremoveEmptyContainers - Remove empty containersmergePaths - Merge pathsremoveUnusedNS - Remove unused namespacessortAttrs - Sort attributessortDefsChildren - Sort defs childrenremoveDesc - Remove description elementsPlugins 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 valuesExamples:
// 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
}
}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 pathsExamples:
// 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
}
}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 gradientsExamples:
// 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
}
}Plugins that handle CSS styles and styling attributes.
'mergeStyles' // Merge multiple style elements
'inlineStyles' // Inline CSS styles
'minifyStyles' // Minify CSS stylesExamples:
// 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
}
}Plugins specifically for path manipulation.
'mergePaths' // Merge multiple paths
'reusePaths' // Reuse identical pathsPlugins 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 childrenExamples:
// sortAttrs - sort attributes alphabetically
{
name: 'sortAttrs',
params: {
xmlnsOrder: 'alphabetical' // or 'front'
}
}
// collapseGroups - remove unnecessary groups
{
name: 'collapseGroups',
params: {
collapseOther: true // Collapse other containers too
}
}Plugins that add content to SVGs.
'addAttributesToSVGElement' // Add attributes to SVG element
'addClassesToSVGElement' // Add classes to SVG element
'prefixIds' // Prefix IDsExamples:
// 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
}
}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