Transform SVG into JSX components using SVGR's core transformation plugin
npx @tessl/cli install tessl/npm-svgr--plugin-jsx@8.1.0@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.
npm install @svgr/plugin-jsx@svgr/coreimport jsxPlugin from "@svgr/plugin-jsx";For CommonJS:
const jsxPlugin = require("@svgr/plugin-jsx");import jsxPlugin from "@svgr/plugin-jsx";
import type { Config, State } from "@svgr/core";
// SVG input
const svgCode = '<svg><path d="M10 10L20 20"/></svg>';
// Configuration
const config: Config = {
jsxRuntime: 'automatic',
typescript: true,
ref: true
};
// State object
const state: State = {
componentName: 'MyIcon',
filePath: 'icons/my-icon.svg'
};
// Transform SVG to JSX
const jsxCode = jsxPlugin(svgCode, config, state);
console.log(jsxCode);
// Output: React component code@svgr/plugin-jsx implements a three-phase transformation pipeline:
svg-parser to convert raw SVG markup into a HAST (Hypertext Abstract Syntax Tree)@svgr/hast-util-to-babel-ast@svgr/babel-preset transformations to generate React component codeThis architecture ensures reliable SVG-to-JSX conversion while providing extensive configuration options for customizing the output through the Babel preset system.
The main plugin function that transforms SVG code into JSX components.
/**
* Transforms SVG code into JSX components through a three-phase process:
* 1. Parse SVG using svg-parser
* 2. Convert HAST to Babel AST
* 3. Apply @svgr/babel-preset transformations
*
* @param code - SVG markup string to transform
* @param config - SVGR configuration options
* @param state - Transformation state and metadata
* @returns Generated JSX component code as string
* @throws Error if transformation fails or unsupported jsxRuntime is specified
*/
declare const jsxPlugin: Plugin;
interface Plugin {
(code: string, config: Config, state: State): string;
}Complete configuration options for controlling SVG to JSX transformation behavior. The plugin uses only the JSX-related subset of the full SVGR Config interface.
interface Config {
/** Enable React ref forwarding */
ref?: boolean;
/** Add title prop support for accessibility */
titleProp?: boolean;
/** Add desc prop support for accessibility */
descProp?: boolean;
/** Props expansion behavior: true, false, 'start', or 'end' */
expandProps?: boolean | 'start' | 'end';
/** Include width/height attributes in output */
dimensions?: boolean;
/** Icon mode settings - boolean or size as string/number */
icon?: boolean | string | number;
/** Enable React Native mode */
native?: boolean;
/** Custom SVG attributes to add */
svgProps?: { [key: string]: string };
/** Attribute value replacements */
replaceAttrValues?: { [key: string]: string };
/** Generate TypeScript code */
typescript?: boolean;
/** Custom template function for component generation */
template?: TransformOptions['template'];
/** Wrap component in React.memo */
memo?: boolean;
/** Export type preference: 'named' or 'default' */
exportType?: 'named' | 'default';
/** Name for named exports when exportType is 'named' */
namedExport?: string;
/** JSX runtime mode */
jsxRuntime?: 'classic' | 'classic-preact' | 'automatic';
/** Custom JSX runtime import configuration */
jsxRuntimeImport?: JsxRuntimeImport;
/** Custom Babel configuration for JSX transformation */
jsx?: { babelConfig?: BabelTransformOptions };
}Configuration for custom JSX runtime imports when using non-standard JSX transformations.
interface JsxRuntimeImport {
/** Import source module name */
source: string;
/** Namespace import name (e.g., 'React' for import * as React) */
namespace?: string;
/** Named import specifiers (e.g., ['h'] for import { h }) */
specifiers?: string[];
/** Default import name (e.g., 'React' for import React) */
defaultSpecifier?: string;
}Transformation state and metadata passed through the plugin pipeline.
interface State {
/** Source file path for the SVG being transformed */
filePath?: string;
/** Generated component name for the output */
componentName: string;
/** Information about the calling context */
caller?: {
/** Name of the calling tool or system */
name?: string;
/** Previous export result from earlier transformations */
previousExport?: string | null;
/** Default plugins for the caller context */
defaultPlugins?: ConfigPlugin[];
};
}
type ConfigPlugin = string | Plugin;The plugin supports multiple JSX runtime configurations:
const config = { jsxRuntime: 'classic' }; // or undefined/null
// Generates: import * as React from "react"const config = { jsxRuntime: 'classic-preact' };
// Generates: import { h } from "preact"const config = { jsxRuntime: 'automatic' };
// Uses new JSX transform - no manual React import requiredconst config = {
jsxRuntimeImport: {
source: 'my-jsx-runtime',
specifiers: ['jsx', 'jsxs']
}
};
// Generates: import { jsx, jsxs } from "my-jsx-runtime"
// Alternative: Namespace import
const config2 = {
jsxRuntimeImport: {
source: 'solid-js/web',
namespace: 'Solid'
}
};
// Generates: import * as Solid from "solid-js/web"
// Alternative: Default import
const config3 = {
jsxRuntimeImport: {
source: 'vue',
defaultSpecifier: 'Vue'
}
};
// Generates: import Vue from "vue"The plugin throws Error exceptions in the following cases:
config.jsxRuntime contains an unsupported value (message: Unsupported "jsxRuntime" "<value>")Unable to generate SVG file)try {
const result = jsxPlugin(svgCode, config, state);
} catch (error) {
if (error.message.includes('Unsupported "jsxRuntime"')) {
// Handle unsupported JSX runtime
console.error('Invalid jsxRuntime configuration:', error.message);
// Fallback to default runtime
const fallbackResult = jsxPlugin(svgCode, { ...config, jsxRuntime: 'classic' }, state);
} else if (error.message === 'Unable to generate SVG file') {
// Handle Babel transformation failure
console.error('Babel transformation failed. Check SVG syntax and configuration.');
} else {
// Handle SVG parsing errors
console.error('SVG parsing failed:', error.message);
}
}Common Error Scenarios:
interface BabelTransformOptions {
[key: string]: any;
}
interface TransformOptions {
template?: any;
}