Fix no exported member 'ReactComponent' when importing svg in react and vite

Aron Schüler Published


The error

When upgrading the packages of one of my react + vite projects, I introduced the following error to my codebase:

Module '"*.svg"' has no exported member 'ReactComponent'. Did you mean to use 'import ReactComponent from "*.svg"' instead?

import { ReactComponent as MyIcon } from "@/assets/icons/MyIcon.svg";

This is an error that is produced by upgrading vite-plugin-svgr from major version 3 to 4 and above. vite-plugin-svgr is a vite plugin that is used to transform SVGs into React components. To fix this error, we have to do two things.

Issue 1: named exports

The first thing we have to adapt are the named exports. These were changed into default exports in version 4 of vite-plugin-svgr. So, if your import in a component looked like:

import { ReactComponent as MyIcon } from "@/assets/icons/MyIcon.svg";

we now have to write

import MyIcon from "@/assets/icons/MyIcon.svg";

This will resolve the errors with the imports. However, this will leave us with a new error:

error TS2322: Type '{ "data-testid": string; className: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'className' does not exist on type 'IntrinsicAttributes'.

This needs another modification, which we will do in the next step.

Issue 2: Import svg as react component

To get the usual attributes of react elements to show up (such as className) we need to import the svg as a react component. To do this, we have to add ?react after the filename path. Going back to the previous mentioned import, this would change the import again from import MyIcon from "@/assets/icons/MyIcon.svg"; to import MyIcon from "@/assets/icons/MyIcon.svg?react";

This will fix your imports and make your project build again!


Related Posts

Find posts on similar topics:


Support me via buymeacoffee

If I helped you solve a problem or you just like my content, consider supporting me by buying me a coffee.

Buy me a coffee

Comments