How to use SVGs as React Components using Vite and TypeScript in your application.
1. Install vite-plugin-svgr
This plugin transforms SVG files into React components. Choose your package manager to install:
npm install --save-dev vite-plugin-svgr
yarn add -D vite-plugin-svgr
pnpm add -D vite-plugin-svgr
2. Setup vite.config.ts
- First, import the plugin:
import svgr from "vite-plugin-svgr";
- Next, add the plugin to your
defineConfig
:
svgr()
- The finished structure should look like this:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), svgr()]
});
3. Add Types to vite-env.d.ts
- Enable TypeScript support for SVG props like
className
,width
, andheight
.
/// <reference types="vite-plugin-svgr/client" />
4. Import with ?react
suffix and use SVG as Component
- Import the SVG file with the
?react
suffix:
import Logo from "./assets/icons/logo.svg?react";
- Use the imported SVG as a React component:
<Logo className="fill-red-500 size-8" />
Contact
- YouTube: Vrauuss Softwares
- GitHub: Vrauuss Softwares
Blog
Coming soon…
Article
- YouTube: How to import SVG as React component
- DEV.to: How to import SVG as React component
References
- GitHub: vite-plugin-svgr
- StackOverflow: Unable to import SVG with Vite as React Component
Top comments (1)
Here my vite.config.ts do not have :
import react from "@vitejs/plugin-react";
and
plugins: [svgr(), tailwindcss()],
but all is working fine...