You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite构建React项目导入SVG时ReactComponent报错求助

Vite React项目中导入SVG作为ReactComponent的解决方案

Vite默认会将SVG作为静态资源处理,导出的是资源URL,而非React组件,所以你用{ ReactComponent as GithubIcon }解构导入会报错。以下是几种可行的解决方法:

方法一:使用vite-plugin-svgr插件(推荐)

这是最便捷的方式,让Vite支持ReactComponent风格的SVG导入:

  1. 安装插件
    npm install vite-plugin-svgr --save-dev
    # 或使用yarn
    yarn add vite-plugin-svgr -D
    
  2. 修改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()]
    })
    
  3. (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组件:

  1. 创建新组件文件(如GithubIcon.jsx)
  2. 将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;
    
  3. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:07:16