Introduction
SVGR takes raw SVG markup and converts it into ready-to-use React components. It handles optimization, formatting, and JSX transformation automatically. The tool is included in Create React App by default and integrates with every major bundler.
What SVGR Does
- Converts SVG files into React functional components with proper JSX
- Optimizes SVG markup using SVGO before transformation
- Supports Webpack, Vite, Rollup, and Next.js through dedicated plugins
- Provides a Node.js API for programmatic transformations
- Generates TypeScript declarations when configured
Architecture Overview
SVGR processes SVGs through a plugin pipeline. First, SVGO optimizes the raw SVG by removing unnecessary attributes and metadata. Then a JSX transformer converts SVG elements to valid JSX, handling attribute renaming (class to className, etc.). Finally, a template engine wraps the JSX in a React component export. Each step is configurable and replaceable.
Self-Hosting & Configuration
- CLI usage:
npx @svgr/cli -- file.svgfor one-off conversions - Webpack: add
@svgr/webpackas a loader for .svg imports - Vite: use
vite-plugin-svgrfor Vite-based projects - Configure via
.svgrrc.jsonor thesvgrkey in package.json - Control SVGO optimizations, TypeScript output, and component templates through config
Key Features
- Zero-config setup with sensible defaults for most projects
- Custom component templates for full control over the generated code
- Named and default export modes for flexible import patterns
- Built-in SVGO integration for automatic SVG optimization
- Playground at svgr.dev for quick online conversion testing
Comparison with Similar Tools
- react-svg — loads SVGs at runtime via fetch; no build-time transformation
- vite-plugin-svgr — Vite wrapper around SVGR; same engine, Vite-specific API
- svg-inline-react — inlines SVG strings as dangerouslySetInnerHTML; less safe
- react-inlinesvg — runtime SVG loading with caching; adds bundle weight
- Manual copy-paste — works for few icons but does not scale or optimize
FAQ
Q: How do I use SVGR with Next.js?
A: Install @svgr/webpack and configure next.config.js to use it as a Webpack loader for .svg files.
Q: Can I generate TypeScript components?
A: Yes. Set typescript: true in your SVGR config to emit .tsx files with proper type annotations.
Q: Does SVGR work with Vite?
A: Yes. Use the vite-plugin-svgr package, which wraps SVGR as a Vite plugin.
Q: Can I customize the generated component template? A: Yes. Provide a custom template function in your config that receives the JSX AST and returns the component code you want.