Update October 2023 – vite-plugin-svgr
version ^4.0.0
When importing your SVG file using vite-plugin-svgr
(see below), make sure to use the newly added ?react
query suffix on your imported file, which allows you to use the default export and skip the ReactComponent
aliasing:
import ReactLogo from './assets/react.svg?react'
<ReactLogo />
If you’re using TypeScript, you’ll also need to add the following at the very top of your file (before the import
statements):
/// <reference types="vite-plugin-svgr/client" />
Update 2023
👉 Use vite-plugin-svgr
- Add
SVGR
to the project
yarn add vite-plugin-svgr
- Register the plugin
SVGR
to vite invite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react(),
svgr({
svgrOptions: {
// svgr options
},
}),
],
})
- In
App.tsx
import SVG as React Component :
import { ReactComponent as ReactLogo } from './assets/react.svg'
<ReactLogo />
Stackblitz Examples:
- standard project
- using Dynamic SVG project
References:
- Learn more about SVGR at https://react-svgr.com/docs/ecosystem/#articles
- plugin options
- list of SVGR options that can be added to
svgrOptions:{}
:
Bonus:
- Dynamic SVG component by Amit Mondal
Note:
Previous plugin @honkhonk/vite-plugin-svgr is deprecated (thanks Richard Fernandez for pointing it)