Transform SVG into JSX components using SVGR's core transformation plugin
npx @tessl/cli install tessl/npm-svgr--plugin-jsx@8.1.00
# @svgr/plugin-jsx
1
2
@svgr/plugin-jsx is the core transformation plugin for SVGR that converts SVG markup into JSX components. It operates through a three-phase process: parsing SVG using svg-parser, converting the HAST (Hypertext Abstract Syntax Tree) into a Babel AST, and applying @svgr/babel-preset transformations to generate React components.
3
4
## Package Information
5
6
- **Package Name**: @svgr/plugin-jsx
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @svgr/plugin-jsx`
10
- **Peer Dependencies**: `@svgr/core`
11
12
## Core Imports
13
14
```typescript
15
import jsxPlugin from "@svgr/plugin-jsx";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const jsxPlugin = require("@svgr/plugin-jsx");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import jsxPlugin from "@svgr/plugin-jsx";
28
import type { Config, State } from "@svgr/core";
29
30
// SVG input
31
const svgCode = '<svg><path d="M10 10L20 20"/></svg>';
32
33
// Configuration
34
const config: Config = {
35
jsxRuntime: 'automatic',
36
typescript: true,
37
ref: true
38
};
39
40
// State object
41
const state: State = {
42
componentName: 'MyIcon',
43
filePath: 'icons/my-icon.svg'
44
};
45
46
// Transform SVG to JSX
47
const jsxCode = jsxPlugin(svgCode, config, state);
48
console.log(jsxCode);
49
// Output: React component code
50
```
51
52
## Architecture
53
54
@svgr/plugin-jsx implements a three-phase transformation pipeline:
55
56
1. **SVG Parsing**: Uses `svg-parser` to convert raw SVG markup into a HAST (Hypertext Abstract Syntax Tree)
57
2. **AST Conversion**: Transforms the HAST into a Babel AST using `@svgr/hast-util-to-babel-ast`
58
3. **JSX Generation**: Applies `@svgr/babel-preset` transformations to generate React component code
59
60
This architecture ensures reliable SVG-to-JSX conversion while providing extensive configuration options for customizing the output through the Babel preset system.
61
62
## Capabilities
63
64
### JSX Plugin Function
65
66
The main plugin function that transforms SVG code into JSX components.
67
68
```typescript { .api }
69
/**
70
* Transforms SVG code into JSX components through a three-phase process:
71
* 1. Parse SVG using svg-parser
72
* 2. Convert HAST to Babel AST
73
* 3. Apply @svgr/babel-preset transformations
74
*
75
* @param code - SVG markup string to transform
76
* @param config - SVGR configuration options
77
* @param state - Transformation state and metadata
78
* @returns Generated JSX component code as string
79
* @throws Error if transformation fails or unsupported jsxRuntime is specified
80
*/
81
declare const jsxPlugin: Plugin;
82
83
interface Plugin {
84
(code: string, config: Config, state: State): string;
85
}
86
```
87
88
### Configuration Interface
89
90
Complete configuration options for controlling SVG to JSX transformation behavior. The plugin uses only the JSX-related subset of the full SVGR Config interface.
91
92
```typescript { .api }
93
interface Config {
94
/** Enable React ref forwarding */
95
ref?: boolean;
96
/** Add title prop support for accessibility */
97
titleProp?: boolean;
98
/** Add desc prop support for accessibility */
99
descProp?: boolean;
100
/** Props expansion behavior: true, false, 'start', or 'end' */
101
expandProps?: boolean | 'start' | 'end';
102
/** Include width/height attributes in output */
103
dimensions?: boolean;
104
/** Icon mode settings - boolean or size as string/number */
105
icon?: boolean | string | number;
106
/** Enable React Native mode */
107
native?: boolean;
108
/** Custom SVG attributes to add */
109
svgProps?: { [key: string]: string };
110
/** Attribute value replacements */
111
replaceAttrValues?: { [key: string]: string };
112
/** Generate TypeScript code */
113
typescript?: boolean;
114
/** Custom template function for component generation */
115
template?: TransformOptions['template'];
116
/** Wrap component in React.memo */
117
memo?: boolean;
118
/** Export type preference: 'named' or 'default' */
119
exportType?: 'named' | 'default';
120
/** Name for named exports when exportType is 'named' */
121
namedExport?: string;
122
/** JSX runtime mode */
123
jsxRuntime?: 'classic' | 'classic-preact' | 'automatic';
124
/** Custom JSX runtime import configuration */
125
jsxRuntimeImport?: JsxRuntimeImport;
126
/** Custom Babel configuration for JSX transformation */
127
jsx?: { babelConfig?: BabelTransformOptions };
128
}
129
```
130
131
### JSX Runtime Import Configuration
132
133
Configuration for custom JSX runtime imports when using non-standard JSX transformations.
134
135
```typescript { .api }
136
interface JsxRuntimeImport {
137
/** Import source module name */
138
source: string;
139
/** Namespace import name (e.g., 'React' for import * as React) */
140
namespace?: string;
141
/** Named import specifiers (e.g., ['h'] for import { h }) */
142
specifiers?: string[];
143
/** Default import name (e.g., 'React' for import React) */
144
defaultSpecifier?: string;
145
}
146
```
147
148
### State Interface
149
150
Transformation state and metadata passed through the plugin pipeline.
151
152
```typescript { .api }
153
interface State {
154
/** Source file path for the SVG being transformed */
155
filePath?: string;
156
/** Generated component name for the output */
157
componentName: string;
158
/** Information about the calling context */
159
caller?: {
160
/** Name of the calling tool or system */
161
name?: string;
162
/** Previous export result from earlier transformations */
163
previousExport?: string | null;
164
/** Default plugins for the caller context */
165
defaultPlugins?: ConfigPlugin[];
166
};
167
}
168
169
type ConfigPlugin = string | Plugin;
170
```
171
172
## JSX Runtime Support
173
174
The plugin supports multiple JSX runtime configurations:
175
176
### Classic React (default)
177
```typescript
178
const config = { jsxRuntime: 'classic' }; // or undefined/null
179
// Generates: import * as React from "react"
180
```
181
182
### Classic Preact
183
```typescript
184
const config = { jsxRuntime: 'classic-preact' };
185
// Generates: import { h } from "preact"
186
```
187
188
### Automatic JSX
189
```typescript
190
const config = { jsxRuntime: 'automatic' };
191
// Uses new JSX transform - no manual React import required
192
```
193
194
### Custom Runtime
195
```typescript
196
const config = {
197
jsxRuntimeImport: {
198
source: 'my-jsx-runtime',
199
specifiers: ['jsx', 'jsxs']
200
}
201
};
202
// Generates: import { jsx, jsxs } from "my-jsx-runtime"
203
204
// Alternative: Namespace import
205
const config2 = {
206
jsxRuntimeImport: {
207
source: 'solid-js/web',
208
namespace: 'Solid'
209
}
210
};
211
// Generates: import * as Solid from "solid-js/web"
212
213
// Alternative: Default import
214
const config3 = {
215
jsxRuntimeImport: {
216
source: 'vue',
217
defaultSpecifier: 'Vue'
218
}
219
};
220
// Generates: import Vue from "vue"
221
```
222
223
## Error Handling
224
225
The plugin throws `Error` exceptions in the following cases:
226
227
- **Unsupported JSX Runtime**: When `config.jsxRuntime` contains an unsupported value (message: `Unsupported "jsxRuntime" "<value>"`)
228
- **Transformation Failure**: When Babel transformation fails to generate code (message: `Unable to generate SVG file`)
229
- **Invalid SVG**: When svg-parser cannot parse the input SVG markup
230
231
```typescript
232
try {
233
const result = jsxPlugin(svgCode, config, state);
234
} catch (error) {
235
if (error.message.includes('Unsupported "jsxRuntime"')) {
236
// Handle unsupported JSX runtime
237
console.error('Invalid jsxRuntime configuration:', error.message);
238
// Fallback to default runtime
239
const fallbackResult = jsxPlugin(svgCode, { ...config, jsxRuntime: 'classic' }, state);
240
} else if (error.message === 'Unable to generate SVG file') {
241
// Handle Babel transformation failure
242
console.error('Babel transformation failed. Check SVG syntax and configuration.');
243
} else {
244
// Handle SVG parsing errors
245
console.error('SVG parsing failed:', error.message);
246
}
247
}
248
```
249
250
**Common Error Scenarios:**
251
252
- **Invalid SVG Markup**: Malformed XML or unsupported SVG elements
253
- **Babel Configuration Issues**: Invalid template functions or preset options
254
- **Missing Dependencies**: Required peer dependencies not installed
255
- **Runtime Conflicts**: Conflicting JSX runtime specifications
256
257
## Types
258
259
### Babel Transform Options
260
261
```typescript { .api }
262
interface BabelTransformOptions {
263
[key: string]: any;
264
}
265
266
interface TransformOptions {
267
template?: any;
268
}
269
```