Vite构建React项目导入SVG时ReactComponent报错求助
Vite React项目中导入SVG作为ReactComponent的解决方案
Vite默认会将SVG作为静态资源处理,导出的是资源URL,而非React组件,所以你用{ ReactComponent as GithubIcon }解构导入会报错。以下是几种可行的解决方法:
方法一:使用vite-plugin-svgr插件(推荐)
这是最便捷的方式,让Vite支持ReactComponent风格的SVG导入:
- 安装插件
npm install vite-plugin-svgr --save-dev # 或使用yarn yarn add vite-plugin-svgr -D - 修改Vite配置文件(
vite.config.js或vite.config.ts)import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import svgr from 'vite-plugin-svgr' export default defineConfig({ plugins: [react(), svgr()] }) - (TypeScript项目可选)添加类型声明
在项目src目录下创建svg.d.ts文件,避免类型报错:
配置完成后,你原来的导入代码就能正常运行。declare module '*.svg' { import React from 'react'; const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>; export default ReactComponent; export { ReactComponent }; }
方法二:手动将SVG转为React组件
如果不想安装插件,可直接把SVG代码封装成React组件:
- 创建新组件文件(如
GithubIcon.jsx) - 将
github.svg内的代码复制到组件中,导出为函数组件:import React from 'react'; const GithubIcon = () => { return ( <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> {/* 粘贴github.svg中的所有内部元素,比如path、circle等 */} </svg> ); }; export default GithubIcon; - 在App组件中导入使用:
import GithubIcon from './GithubIcon';
方法三:作为图片资源导入(无需组件化)
如果不需要动态修改SVG样式(如颜色、尺寸),可直接用img标签显示:
import githubImg from './assets/img/github.svg'; function App() { return ( <header> <nav> <div> <h1>DSMovie</h1> <a href="https://github.com/devsuperior"> <div> <img src={githubImg} alt="Github" /> <p>/devsuperior</p> </div> </a> </div> </nav> </header> ) }
内容的提问来源于stack exchange,提问作者Marcb7
相关产品推荐
相关产品推荐

