I'm trying to include an SVG in a page while using React + Typescript + Vite. I've been looking at blogs like https://dev.to/cassidoo/importing-svg-files-as-react-components-with-vite-l3n and they all say the same thing, use vite-plugin-svgr, but it isn't working for me.
Here is my vite.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()],
test: {
testTimeout: 2000,
hookTimeout: 2000,
},
build: {
minify: false,
},
});
Here is the import statement of my component
import { ReactComponent as RedDie } from './images/red-die.svg';
Here is my directory structure
src/
App.tsx
images/
red-die.svg
I'm getting the following error in VSCode.
Cannot find module 'assets/red-die.svg' or its corresponding type declarations.
When I try to visit the page I get a 404 message that says
Cannot GET /
Note that I am building the front end and serving it staticly with node rather than using the vite dev server. See Use vite and express at the same time by sharing cookies or something
The api got changed from vite-plugin-svgr npm
SVG files can be imported as React components
import Logo from "./logo.svg?react";
notice the ?react
If you are using TypeScript, there is also a declaration helper for better type inference:
/// <reference types="vite-plugin-svgr/client" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With