or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ast-manipulation.mdcli.mdconfiguration.mdcore-optimization.mddata-uri.mdindex.mdplugins.mdutility-functions.md

core-optimization.mddocs/

0

# Core Optimization

1

2

Main SVG optimization functionality that processes SVG strings through configurable plugin pipelines with support for multiple passes and various output formats.

3

4

## Capabilities

5

6

### Optimize Function

7

8

The core optimization function that processes SVG input through a configurable plugin pipeline.

9

10

```javascript { .api }

11

/**

12

* Optimize SVG content using SVGO plugins

13

* @param input - SVG string to optimize

14

* @param config - Optional configuration object

15

* @returns Optimization result with optimized SVG data

16

*/

17

function optimize(input: string, config?: Config): Output;

18

19

interface Config {

20

/** File path for plugins that need path context */

21

path?: string;

22

/** Pass over SVGs multiple times to ensure all optimizations are applied */

23

multipass?: boolean;

24

/**

25

* Precision of floating point numbers. Will be passed to each plugin that

26

* supports this param.

27

*/

28

floatPrecision?: number;

29

/**

30

* Plugins configuration. By default SVGO uses 'preset-default', but may

31

* contain builtin or custom plugins.

32

*/

33

plugins?: PluginConfig[];

34

/** Options for rendering optimized SVG from AST */

35

js2svg?: StringifyOptions;

36

/** Output as Data URI string */

37

datauri?: DataUri;

38

}

39

40

interface Output {

41

/** Optimized SVG data as string */

42

data: string;

43

}

44

45

type DataUri = 'base64' | 'enc' | 'unenc';

46

```

47

48

**Usage Examples:**

49

50

```javascript

51

import { optimize } from "svgo";

52

53

// Basic optimization with default settings

54

const result = optimize(`

55

<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">

56

<rect x="0" y="0" width="100" height="100" fill="red"/>

57

</svg>

58

`);

59

console.log(result.data);

60

61

// Optimization with custom configuration

62

const result = optimize(svgString, {

63

multipass: true,

64

floatPrecision: 2,

65

plugins: [

66

'preset-default',

67

{

68

name: 'removeAttrs',

69

params: {

70

attrs: ['data-*', 'aria-*']

71

}

72

}

73

]

74

});

75

76

// Pretty-printed output

77

const result = optimize(svgString, {

78

js2svg: {

79

pretty: true,

80

indent: 2

81

}

82

});

83

84

// Data URI output

85

const result = optimize(svgString, {

86

datauri: 'base64'

87

});

88

// result.data will be: "data:image/svg+xml;base64,..."

89

```

90

91

### Plugin Configuration

92

93

Configure which plugins to use and their parameters.

94

95

```javascript { .api }

96

type PluginConfig =

97

| string // Plugin name for builtin plugins with default params

98

| {

99

name: string;

100

params?: any;

101

fn?: Plugin; // Custom plugin function

102

};

103

104

interface Plugin<P = any> {

105

(root: XastRoot, params: P, info: PluginInfo): Visitor | null | void;

106

}

107

```

108

109

**Plugin Configuration Examples:**

110

111

```javascript

112

// Using plugin names (default parameters)

113

{

114

plugins: [

115

'removeDoctype',

116

'removeComments',

117

'cleanupAttrs'

118

]

119

}

120

121

// Using plugin objects with custom parameters

122

{

123

plugins: [

124

'preset-default', // Uses all default plugins

125

{

126

name: 'convertColors',

127

params: {

128

currentColor: true,

129

names2hex: true

130

}

131

},

132

{

133

name: 'removeAttrs',

134

params: {

135

attrs: ['data-*', 'class']

136

}

137

}

138

]

139

}

140

141

// Disabling plugins from preset-default

142

{

143

plugins: [

144

{

145

name: 'preset-default',

146

params: {

147

overrides: {

148

removeViewBox: false, // Disable this plugin

149

cleanupIds: {

150

minify: false // Keep long IDs

151

}

152

}

153

}

154

}

155

]

156

}

157

```

158

159

### Output Configuration

160

161

Control how the optimized SVG is formatted and output.

162

163

```javascript { .api }

164

interface StringifyOptions {

165

/** DOCTYPE formatting */

166

doctypeStart?: string;

167

doctypeEnd?: string;

168

/** Processing instruction formatting */

169

procInstStart?: string;

170

procInstEnd?: string;

171

/** Tag formatting */

172

tagOpenStart?: string;

173

tagOpenEnd?: string;

174

tagCloseStart?: string;

175

tagCloseEnd?: string;

176

tagShortStart?: string;

177

tagShortEnd?: string;

178

/** Attribute formatting */

179

attrStart?: string;

180

attrEnd?: string;

181

/** Comment formatting */

182

commentStart?: string;

183

commentEnd?: string;

184

/** CDATA formatting */

185

cdataStart?: string;

186

cdataEnd?: string;

187

/** Text formatting */

188

textStart?: string;

189

textEnd?: string;

190

/** Indentation (number of spaces or string) */

191

indent?: number | string;

192

/** Entity encoding patterns */

193

regEntities?: RegExp;

194

regValEntities?: RegExp;

195

encodeEntity?: (char: string) => string;

196

/** Enable pretty printing with proper indentation */

197

pretty?: boolean;

198

/** Use self-closing tags where possible */

199

useShortTags?: boolean;

200

/** Line ending style */

201

eol?: 'lf' | 'crlf';

202

/** Add final newline to output */

203

finalNewline?: boolean;

204

}

205

```

206

207

**Output Formatting Examples:**

208

209

```javascript

210

// Pretty-printed SVG

211

const result = optimize(svgString, {

212

js2svg: {

213

pretty: true,

214

indent: 2,

215

eol: 'lf',

216

finalNewline: true

217

}

218

});

219

220

// Compact output (default)

221

const result = optimize(svgString, {

222

js2svg: {

223

pretty: false,

224

useShortTags: true

225

}

226

});

227

228

// Custom formatting

229

const result = optimize(svgString, {

230

js2svg: {

231

tagOpenEnd: '>',

232

attrStart: ' ',

233

attrEnd: '',

234

indent: '\t' // Use tabs instead of spaces

235

}

236

});

237

```

238

239

### Multipass Optimization

240

241

Enable multiple optimization passes for maximum compression.

242

243

```javascript { .api }

244

interface Config {

245

/**

246

* Pass over SVGs multiple times to ensure all optimizations are applied.

247

* Maximum of 10 passes, stops early if no size reduction achieved.

248

*/

249

multipass?: boolean;

250

}

251

```

252

253

**Multipass Example:**

254

255

```javascript

256

// Enable multipass optimization

257

const result = optimize(svgString, {

258

multipass: true, // Will run up to 10 passes or until no improvement

259

plugins: ['preset-default']

260

});

261

262

// Multipass is especially useful for complex SVGs where plugins

263

// can create new optimization opportunities for other plugins

264

```

265

266

### Error Handling

267

268

The optimize function handles parsing errors gracefully.

269

270

```javascript

271

import { optimize } from "svgo";

272

273

try {

274

const result = optimize(invalidSvgString);

275

console.log(result.data);

276

} catch (error) {

277

if (error.name === 'SvgoParserError') {

278

console.error('SVG parsing failed:', error.message);

279

console.error('Line:', error.line, 'Column:', error.column);

280

} else {

281

console.error('Optimization failed:', error.message);

282

}

283

}

284

```

285

286

### Node.js vs Browser Differences

287

288

The Node.js version includes additional functionality not available in the browser version.

289

290

**Node.js specific features:**

291

- Configuration file loading (`loadConfig`)

292

- File system operations

293

- Platform-specific line ending defaults (CRLF on Windows, LF elsewhere)

294

295

**Browser version limitations:**

296

- No config file loading

297

- No file system access

298

- Uses LF line endings by default