Node.js library and command-line application for optimizing SVG vector graphics files
—
Main SVG optimization functionality that processes SVG strings through configurable plugin pipelines with support for multiple passes and various output formats.
The core optimization function that processes SVG input through a configurable plugin pipeline.
/**
* Optimize SVG content using SVGO plugins
* @param input - SVG string to optimize
* @param config - Optional configuration object
* @returns Optimization result with optimized SVG data
*/
function optimize(input: string, config?: Config): Output;
interface Config {
/** File path for plugins that need path context */
path?: string;
/** Pass over SVGs multiple times to ensure all optimizations are applied */
multipass?: boolean;
/**
* Precision of floating point numbers. Will be passed to each plugin that
* supports this param.
*/
floatPrecision?: number;
/**
* Plugins configuration. By default SVGO uses 'preset-default', but may
* contain builtin or custom plugins.
*/
plugins?: PluginConfig[];
/** Options for rendering optimized SVG from AST */
js2svg?: StringifyOptions;
/** Output as Data URI string */
datauri?: DataUri;
}
interface Output {
/** Optimized SVG data as string */
data: string;
}
type DataUri = 'base64' | 'enc' | 'unenc';Usage Examples:
import { optimize } from "svgo";
// Basic optimization with default settings
const result = optimize(`
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<rect x="0" y="0" width="100" height="100" fill="red"/>
</svg>
`);
console.log(result.data);
// Optimization with custom configuration
const result = optimize(svgString, {
multipass: true,
floatPrecision: 2,
plugins: [
'preset-default',
{
name: 'removeAttrs',
params: {
attrs: ['data-*', 'aria-*']
}
}
]
});
// Pretty-printed output
const result = optimize(svgString, {
js2svg: {
pretty: true,
indent: 2
}
});
// Data URI output
const result = optimize(svgString, {
datauri: 'base64'
});
// result.data will be: "data:image/svg+xml;base64,..."Configure which plugins to use and their parameters.
type PluginConfig =
| string // Plugin name for builtin plugins with default params
| {
name: string;
params?: any;
fn?: Plugin; // Custom plugin function
};
interface Plugin<P = any> {
(root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;
}Plugin Configuration Examples:
// Using plugin names (default parameters)
{
plugins: [
'removeDoctype',
'removeComments',
'cleanupAttrs'
]
}
// Using plugin objects with custom parameters
{
plugins: [
'preset-default', // Uses all default plugins
{
name: 'convertColors',
params: {
currentColor: true,
names2hex: true
}
},
{
name: 'removeAttrs',
params: {
attrs: ['data-*', 'class']
}
}
]
}
// Disabling plugins from preset-default
{
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false, // Disable this plugin
cleanupIds: {
minify: false // Keep long IDs
}
}
}
}
]
}Control how the optimized SVG is formatted and output.
interface StringifyOptions {
/** DOCTYPE formatting */
doctypeStart?: string;
doctypeEnd?: string;
/** Processing instruction formatting */
procInstStart?: string;
procInstEnd?: string;
/** Tag formatting */
tagOpenStart?: string;
tagOpenEnd?: string;
tagCloseStart?: string;
tagCloseEnd?: string;
tagShortStart?: string;
tagShortEnd?: string;
/** Attribute formatting */
attrStart?: string;
attrEnd?: string;
/** Comment formatting */
commentStart?: string;
commentEnd?: string;
/** CDATA formatting */
cdataStart?: string;
cdataEnd?: string;
/** Text formatting */
textStart?: string;
textEnd?: string;
/** Indentation (number of spaces or string) */
indent?: number | string;
/** Entity encoding patterns */
regEntities?: RegExp;
regValEntities?: RegExp;
encodeEntity?: (char: string) => string;
/** Enable pretty printing with proper indentation */
pretty?: boolean;
/** Use self-closing tags where possible */
useShortTags?: boolean;
/** Line ending style */
eol?: 'lf' | 'crlf';
/** Add final newline to output */
finalNewline?: boolean;
}Output Formatting Examples:
// Pretty-printed SVG
const result = optimize(svgString, {
js2svg: {
pretty: true,
indent: 2,
eol: 'lf',
finalNewline: true
}
});
// Compact output (default)
const result = optimize(svgString, {
js2svg: {
pretty: false,
useShortTags: true
}
});
// Custom formatting
const result = optimize(svgString, {
js2svg: {
tagOpenEnd: '>',
attrStart: ' ',
attrEnd: '',
indent: '\t' // Use tabs instead of spaces
}
});Enable multiple optimization passes for maximum compression.
interface Config {
/**
* Pass over SVGs multiple times to ensure all optimizations are applied.
* Maximum of 10 passes, stops early if no size reduction achieved.
*/
multipass?: boolean;
}Multipass Example:
// Enable multipass optimization
const result = optimize(svgString, {
multipass: true, // Will run up to 10 passes or until no improvement
plugins: ['preset-default']
});
// Multipass is especially useful for complex SVGs where plugins
// can create new optimization opportunities for other pluginsThe optimize function handles parsing errors gracefully.
import { optimize } from "svgo";
try {
const result = optimize(invalidSvgString);
console.log(result.data);
} catch (error) {
if (error.name === 'SvgoParserError') {
console.error('SVG parsing failed:', error.message);
console.error('Line:', error.line, 'Column:', error.column);
} else {
console.error('Optimization failed:', error.message);
}
}The Node.js version includes additional functionality not available in the browser version.
Node.js specific features:
loadConfig)Browser version limitations:
Install with Tessl CLI
npx tessl i tessl/npm-svgo