or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-svgr--plugin-jsx

Transform SVG into JSX components using SVGR's core transformation plugin

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@svgr/plugin-jsx@8.1.x

To install, run

npx @tessl/cli install tessl/npm-svgr--plugin-jsx@8.1.0

index.mddocs/

@svgr/plugin-jsx

@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.

Package Information

  • Package Name: @svgr/plugin-jsx
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @svgr/plugin-jsx
  • Peer Dependencies: @svgr/core

Core Imports

import jsxPlugin from "@svgr/plugin-jsx";

For CommonJS:

const jsxPlugin = require("@svgr/plugin-jsx");

Basic Usage

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

Architecture

@svgr/plugin-jsx implements a three-phase transformation pipeline:

  1. SVG Parsing: Uses svg-parser to convert raw SVG markup into a HAST (Hypertext Abstract Syntax Tree)
  2. AST Conversion: Transforms the HAST into a Babel AST using @svgr/hast-util-to-babel-ast
  3. JSX Generation: Applies @svgr/babel-preset transformations to generate React component code

This architecture ensures reliable SVG-to-JSX conversion while providing extensive configuration options for customizing the output through the Babel preset system.

Capabilities

JSX Plugin Function

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;
}

Configuration Interface

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 };
}

JSX Runtime Import Configuration

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;
}

State Interface

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;

JSX Runtime Support

The plugin supports multiple JSX runtime configurations:

Classic React (default)

const config = { jsxRuntime: 'classic' }; // or undefined/null
// Generates: import * as React from "react"

Classic Preact

const config = { jsxRuntime: 'classic-preact' };
// Generates: import { h } from "preact"

Automatic JSX

const config = { jsxRuntime: 'automatic' };
// Uses new JSX transform - no manual React import required

Custom Runtime

const 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"

Error Handling

The plugin throws Error exceptions in the following cases:

  • Unsupported JSX Runtime: When config.jsxRuntime contains an unsupported value (message: Unsupported "jsxRuntime" "<value>")
  • Transformation Failure: When Babel transformation fails to generate code (message: Unable to generate SVG file)
  • Invalid SVG: When svg-parser cannot parse the input SVG markup
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:

  • Invalid SVG Markup: Malformed XML or unsupported SVG elements
  • Babel Configuration Issues: Invalid template functions or preset options
  • Missing Dependencies: Required peer dependencies not installed
  • Runtime Conflicts: Conflicting JSX runtime specifications

Types

Babel Transform Options

interface BabelTransformOptions {
  [key: string]: any;
}

interface TransformOptions {
  template?: any;
}