0
# Plugin System
1
2
Comprehensive plugin architecture with 50+ built-in plugins for SVG optimization, organized into categories like cleanup, removal, conversion, and styling operations.
3
4
## Capabilities
5
6
### Built-in Plugins
7
8
Access to all built-in SVGO plugins.
9
10
```javascript { .api }
11
/**
12
* Array of all built-in SVGO plugins
13
*/
14
const builtinPlugins: ReadonlyArray<BuiltinPluginOrPreset<string, any>>;
15
16
interface BuiltinPluginOrPreset<Name extends string, Params> {
17
/** Name of the plugin, also known as the plugin ID */
18
name: Name;
19
/** Optional description of what the plugin does */
20
description?: string;
21
/** Plugin implementation function */
22
fn: Plugin<Params>;
23
/** If the plugin is itself a preset that invokes other plugins */
24
isPreset?: true;
25
/**
26
* If the plugin is a preset that invokes other plugins, this returns an
27
* array of the plugins in the preset in the order that they are invoked
28
*/
29
plugins?: ReadonlyArray<BuiltinPlugin<string, Object>>;
30
}
31
32
interface Plugin<P = any> {
33
(root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;
34
}
35
```
36
37
**Usage Examples:**
38
39
```javascript
40
import { builtinPlugins } from "svgo";
41
42
// List all available plugins
43
console.log(builtinPlugins.map(plugin => plugin.name));
44
45
// Find a specific plugin
46
const removeComments = builtinPlugins.find(p => p.name === 'removeComments');
47
console.log(removeComments.description);
48
49
// Check if a plugin is a preset
50
const presetDefault = builtinPlugins.find(p => p.name === 'preset-default');
51
if (presetDefault.isPreset) {
52
console.log('Preset includes:', presetDefault.plugins.map(p => p.name));
53
}
54
```
55
56
### Plugin Configuration
57
58
Configure individual plugins with custom parameters.
59
60
```javascript { .api }
61
type PluginConfig =
62
| string // Plugin name for builtin plugins with default params
63
| {
64
name: string;
65
params?: any;
66
fn?: Plugin; // Custom plugin function
67
}
68
| CustomPlugin;
69
70
interface CustomPlugin<T = any> {
71
name: string;
72
fn: Plugin<T>;
73
params?: T;
74
}
75
```
76
77
### Default Preset
78
79
The default plugin preset that runs when no plugins are specified.
80
81
```javascript { .api }
82
/**
83
* Default preset configuration with 35 optimization plugins
84
*/
85
interface PresetDefaultConfig {
86
/** Global floating point precision */
87
floatPrecision?: number;
88
/** Override settings for individual plugins */
89
overrides?: {
90
[PluginName in DefaultPluginNames]?: PluginParams[PluginName] | false;
91
};
92
}
93
```
94
95
**Default Preset Plugins (in execution order):**
96
97
1. `removeDoctype` - Remove DOCTYPE declarations
98
2. `removeXMLProcInst` - Remove XML processing instructions
99
3. `removeComments` - Remove XML comments
100
4. `removeDeprecatedAttrs` - Remove deprecated attributes
101
5. `removeMetadata` - Remove `<metadata>` elements
102
6. `removeEditorsNSData` - Remove editor namespace data
103
7. `cleanupAttrs` - Clean up attributes
104
8. `mergeStyles` - Merge multiple `<style>` elements
105
9. `inlineStyles` - Inline CSS styles
106
10. `minifyStyles` - Minify CSS in `<style>` elements
107
11. `cleanupIds` - Clean up IDs
108
12. `removeUselessDefs` - Remove useless `<defs>` elements
109
13. `cleanupNumericValues` - Clean up numeric values
110
14. `convertColors` - Convert colors to shorter formats
111
15. `removeUnknownsAndDefaults` - Remove unknown and default values
112
16. `removeNonInheritableGroupAttrs` - Remove non-inheritable group attributes
113
17. `removeUselessStrokeAndFill` - Remove useless stroke and fill
114
18. `cleanupEnableBackground` - Clean up enable-background
115
19. `removeHiddenElems` - Remove hidden elements
116
20. `removeEmptyText` - Remove empty text elements
117
21. `convertShapeToPath` - Convert shapes to paths
118
22. `convertEllipseToCircle` - Convert ellipses to circles
119
23. `moveElemsAttrsToGroup` - Move element attributes to group
120
24. `moveGroupAttrsToElems` - Move group attributes to elements
121
25. `collapseGroups` - Collapse groups
122
26. `convertPathData` - Convert path data
123
27. `convertTransform` - Convert transforms
124
28. `removeEmptyAttrs` - Remove empty attributes
125
29. `removeEmptyContainers` - Remove empty containers
126
30. `mergePaths` - Merge paths
127
31. `removeUnusedNS` - Remove unused namespaces
128
32. `sortAttrs` - Sort attributes
129
33. `sortDefsChildren` - Sort defs children
130
34. `removeDesc` - Remove description elements
131
132
### Plugin Categories
133
134
#### Cleanup Plugins
135
136
Plugins that clean and normalize SVG content.
137
138
```javascript { .api }
139
// Cleanup attribute values and formatting
140
'cleanupAttrs' // Clean up attributes
141
'cleanupIds' // Clean up IDs
142
'cleanupNumericValues' // Clean up numeric values
143
'cleanupEnableBackground' // Clean up enable-background
144
'cleanupListOfValues' // Clean up list values
145
```
146
147
**Examples:**
148
149
```javascript
150
// cleanupAttrs - removes unnecessary whitespace and normalizes values
151
{
152
name: 'cleanupAttrs',
153
params: {
154
newlines: true, // Remove newlines
155
trim: true, // Trim whitespace
156
spaces: true // Normalize spaces
157
}
158
}
159
160
// cleanupIds - optimizes ID values
161
{
162
name: 'cleanupIds',
163
params: {
164
remove: true, // Remove unused IDs
165
minify: true, // Minify ID names
166
preserve: ['keep-this-id'] // IDs to preserve
167
}
168
}
169
170
// cleanupNumericValues - formats numeric values
171
{
172
name: 'cleanupNumericValues',
173
params: {
174
floatPrecision: 2, // Decimal places
175
leadingZero: true, // Remove leading zeros
176
defaultPx: true // Remove default px units
177
}
178
}
179
```
180
181
#### Removal Plugins
182
183
Plugins that remove unnecessary SVG content.
184
185
```javascript { .api }
186
// Document structure removal
187
'removeDoctype' // Remove DOCTYPE
188
'removeXMLProcInst' // Remove XML processing instructions
189
'removeComments' // Remove comments
190
'removeMetadata' // Remove metadata
191
192
// Content removal
193
'removeDesc' // Remove description elements
194
'removeTitle' // Remove title elements
195
'removeEmptyAttrs' // Remove empty attributes
196
'removeEmptyText' // Remove empty text
197
'removeEmptyContainers' // Remove empty containers
198
'removeHiddenElems' // Remove hidden elements
199
200
// Attribute removal
201
'removeDeprecatedAttrs' // Remove deprecated attributes
202
'removeAttrs' // Remove specific attributes
203
'removeElementsByAttr' // Remove elements by attribute
204
'removeAttributesBySelector' // Remove attributes by selector
205
206
// Advanced removal
207
'removeUselessDefs' // Remove useless definitions
208
'removeUselessStrokeAndFill' // Remove useless stroke and fill
209
'removeUnusedNS' // Remove unused namespaces
210
'removeUnknownsAndDefaults' // Remove unknowns and defaults
211
'removeNonInheritableGroupAttrs' // Remove non-inheritable group attributes
212
'removeEditorsNSData' // Remove editor namespace data
213
'removeRasterImages' // Remove raster images
214
'removeScripts' // Remove scripts
215
'removeStyleElement' // Remove style elements
216
'removeViewBox' // Remove viewBox
217
'removeXlink' // Remove XLink references
218
'removeXMLNS' // Remove XML namespace
219
'removeDimensions' // Remove dimensions
220
'removeOffCanvasPaths' // Remove off-canvas paths
221
```
222
223
**Examples:**
224
225
```javascript
226
// removeAttrs - remove specific attributes
227
{
228
name: 'removeAttrs',
229
params: {
230
attrs: ['data-*', 'class', 'style']
231
}
232
}
233
234
// removeElementsByAttr - remove elements with specific attributes
235
{
236
name: 'removeElementsByAttr',
237
params: {
238
id: ['unwanted-id'],
239
class: ['remove-this']
240
}
241
}
242
243
// removeHiddenElems - remove invisible elements
244
{
245
name: 'removeHiddenElems',
246
params: {
247
isHidden: true, // Remove display:none elements
248
displayNone: true, // Remove opacity:0 elements
249
opacity0: true // Remove visibility:hidden elements
250
}
251
}
252
```
253
254
#### Conversion Plugins
255
256
Plugins that convert SVG elements to more optimal formats.
257
258
```javascript { .api }
259
'convertColors' // Convert colors to shorter formats
260
'convertEllipseToCircle' // Convert ellipses to circles
261
'convertShapeToPath' // Convert shapes to paths
262
'convertPathData' // Convert path data
263
'convertTransform' // Convert transforms
264
'convertStyleToAttrs' // Convert styles to attributes
265
'convertOneStopGradients' // Convert one-stop gradients
266
```
267
268
**Examples:**
269
270
```javascript
271
// convertColors - optimize color values
272
{
273
name: 'convertColors',
274
params: {
275
currentColor: true, // Convert to currentColor
276
names2hex: true, // Convert color names to hex
277
rgb2hex: true, // Convert RGB to hex
278
shorthex: true, // Use short hex when possible
279
shortname: true // Use short color names
280
}
281
}
282
283
// convertPathData - optimize path data
284
{
285
name: 'convertPathData',
286
params: {
287
applyTransforms: true, // Apply transforms to paths
288
applyTransformsStroked: true, // Apply to stroked paths
289
makeArcs: {
290
threshold: 2.5, // Arc conversion threshold
291
tolerance: 0.5 // Arc tolerance
292
},
293
straightCurves: true, // Convert curves to lines
294
lineShorthands: true, // Use line shorthands
295
curveSmoothShorthands: true, // Use curve shorthands
296
floatPrecision: 3, // Float precision
297
transformPrecision: 5, // Transform precision
298
removeUseless: true, // Remove useless commands
299
collapseRepeated: true, // Collapse repeated commands
300
utilizeAbsolute: true, // Use absolute commands when shorter
301
leadingZero: true, // Remove leading zeros
302
negativeExtraSpace: true // Remove extra spaces around negatives
303
}
304
}
305
```
306
307
#### Style Plugins
308
309
Plugins that handle CSS styles and styling attributes.
310
311
```javascript { .api }
312
'mergeStyles' // Merge multiple style elements
313
'inlineStyles' // Inline CSS styles
314
'minifyStyles' // Minify CSS styles
315
```
316
317
**Examples:**
318
319
```javascript
320
// inlineStyles - inline CSS styles as attributes
321
{
322
name: 'inlineStyles',
323
params: {
324
onlyMatchedOnce: true, // Only inline styles used once
325
removeMatchedSelectors: true, // Remove selectors after inlining
326
useMqs: ['', 'screen'], // Media queries to consider
327
usePseudos: [''] // Pseudo-classes to consider
328
}
329
}
330
331
// minifyStyles - minify CSS content
332
{
333
name: 'minifyStyles',
334
params: {
335
restructure: true, // Restructure CSS
336
forceMediaMerge: false, // Force media query merging
337
comments: false // Remove comments
338
}
339
}
340
```
341
342
#### Path Plugins
343
344
Plugins specifically for path manipulation.
345
346
```javascript { .api }
347
'mergePaths' // Merge multiple paths
348
'reusePaths' // Reuse identical paths
349
```
350
351
#### Organization Plugins
352
353
Plugins that reorganize SVG structure.
354
355
```javascript { .api }
356
'moveElemsAttrsToGroup' // Move element attributes to group
357
'moveGroupAttrsToElems' // Move group attributes to elements
358
'collapseGroups' // Collapse unnecessary groups
359
'sortAttrs' // Sort attributes
360
'sortDefsChildren' // Sort defs children
361
```
362
363
**Examples:**
364
365
```javascript
366
// sortAttrs - sort attributes alphabetically
367
{
368
name: 'sortAttrs',
369
params: {
370
xmlnsOrder: 'alphabetical' // or 'front'
371
}
372
}
373
374
// collapseGroups - remove unnecessary groups
375
{
376
name: 'collapseGroups',
377
params: {
378
collapseOther: true // Collapse other containers too
379
}
380
}
381
```
382
383
#### Enhancement Plugins
384
385
Plugins that add content to SVGs.
386
387
```javascript { .api }
388
'addAttributesToSVGElement' // Add attributes to SVG element
389
'addClassesToSVGElement' // Add classes to SVG element
390
'prefixIds' // Prefix IDs
391
```
392
393
**Examples:**
394
395
```javascript
396
// addClassesToSVGElement - add CSS classes to root SVG
397
{
398
name: 'addClassesToSVGElement',
399
params: {
400
classNames: ['optimized', 'icon']
401
}
402
}
403
404
// prefixIds - add prefix to all IDs
405
{
406
name: 'prefixIds',
407
params: {
408
prefix: 'icon-',
409
delim: '' // Delimiter between prefix and ID
410
}
411
}
412
```
413
414
### Custom Plugins
415
416
Create custom optimization plugins.
417
418
```javascript { .api }
419
interface CustomPlugin<T = any> {
420
name: string;
421
fn: Plugin<T>;
422
params?: T;
423
}
424
425
interface Plugin<P = any> {
426
(root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;
427
}
428
429
interface PluginInfo {
430
/** File path if available */
431
path?: string;
432
/** Current multipass iteration count */
433
multipassCount: number;
434
}
435
436
interface Visitor {
437
element?: VisitorNode<XastElement>;
438
text?: VisitorNode<XastText>;
439
comment?: VisitorNode<XastComment>;
440
// ... other node types
441
}
442
443
interface VisitorNode<Node> {
444
enter?: (node: Node, parentNode: XastParent) => void | symbol;
445
exit?: (node: Node, parentNode: XastParent) => void;
446
}
447
```
448
449
**Custom Plugin Examples:**
450
451
```javascript
452
// Custom plugin to remove specific elements
453
const removeCustomElements = {
454
name: 'removeCustomElements',
455
fn: (root, params) => {
456
return {
457
element: {
458
enter(node, parent) {
459
if (params.elements.includes(node.name)) {
460
// Remove this element
461
const index = parent.children.indexOf(node);
462
parent.children.splice(index, 1);
463
}
464
}
465
}
466
};
467
},
468
params: {
469
elements: ['unwanted-element', 'custom-tag']
470
}
471
};
472
473
// Custom plugin to modify attributes
474
const modifyAttributes = {
475
name: 'modifyAttributes',
476
fn: (root, params) => {
477
return {
478
element: {
479
enter(node) {
480
if (node.name === 'rect') {
481
// Round all numeric attributes
482
Object.keys(node.attributes).forEach(attr => {
483
const value = parseFloat(node.attributes[attr]);
484
if (!isNaN(value)) {
485
node.attributes[attr] = Math.round(value).toString();
486
}
487
});
488
}
489
}
490
}
491
};
492
}
493
};
494
495
// Use custom plugins
496
import { optimize } from "svgo";
497
498
const result = optimize(svgString, {
499
plugins: [
500
'preset-default',
501
removeCustomElements,
502
modifyAttributes
503
]
504
});
505
```