Unable to import SVG with Vite as ReactComponent

Viewed 11520

Tried to use this library: vite-plugin-react-svg

and had no success by importing it like:

import { ExternalLink } from 'assets/svg/link-external.svg?component';

Are there any workarounds for this issue?

The error i got before was the following:

import { ReactComponent as ExternalLink } from 'assets/svg/link-external.svg';

//Uncaught SyntaxError: 
  The requested module '/src/assets/svg/link-external.svg?import'
  does not provide an export named 'ReactComponent'
4 Answers

Use vite-plugin-svgr

  1. Add SVGR to the project

yarn add -D @honkhonk/vite-plugin-svgr

  1. Add the plugin SVGR to vite in vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from '@honkhonk/vite-plugin-svgr'

export default defineConfig({
  plugins: [ svgr(), react()]
})
  1. In App.tsx import SVG as React Component by adding ?component on the svg's import directive :
import Happy from './assets/svg/happy.svg?component'

<Happy />

You can find more informations about SVGR at https://react-svgr.com/docs/ecosystem/#articles

Anyone having issues with the accepted answer, try the solution described in this package: https://www.npmjs.com/package/vite-plugin-svgr

import { ReactComponent as Logo } from './logo.svg'

For some reason, I couldn't build using the accepted answer

I was able to solve this issue after installing this package:

npm i vite-plugin-svgr

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import svgr from 'vite-plugin-svgr'; // make sure to import it

export default defineConfig({
    plugins: [react(), svgr()],
});

// App.jsx
import {ReactComponent as ExternalLink} from './assets/svg/link-external.svg';

<ExternalLink />

You can avoid svgr by importing like this an assigning to an img

import logo from "./logo-login.svg"
<img src={logo} className="w-24 inline-block" alt="logo" />
Related