Answer a question

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'

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

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐