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

Vite中导入SVG为ReactComponent报错:ambiguous indirect export: ReactComponent

解决Vite + vite-plugin-svgr + React + TypeScript中SVG组件导入的语法错误

问题根源

你遇到的Uncaught SyntaxError: ambiguous indirect export: ReactComponent错误,核心原因是自定义custom.d.ts中的SVG模块声明与vite-plugin-svgr自带的类型定义发生冲突,导致模块解析逻辑出现歧义。

分步解决方法

1. 删除重复的类型声明

直接移除custom.d.ts中针对*.svg的模块声明代码——vite-plugin-svgr已经内置了完整的类型定义,自定义声明会打乱TypeScript和Vite的模块解析逻辑。

2. 确认Vite插件配置正确

确保vite.config.ts中正确注册vite-plugin-svgr插件:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import svgr from 'vite-plugin-svgr'

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

3. 使用正确的SVG导入方式

两种可靠的导入方式可选:

  • 命名导入(保留你原有的写法,需确保无类型冲突):
    import { ReactComponent as ProfileIcon } from '../assets/profile.svg'
    
    export function Example() {
      return (
        <div>
          <p>blahblahblah</p>
          <ProfileIcon />
        </div>
      )
    }
    
  • 带后缀的默认导入(更明确,避免与普通SVG资源导入混淆):
    import ProfileIcon from '../assets/profile.svg?react'
    
    export function Example() {
      return (
        <div>
          <p>blahblahblah</p>
          <ProfileIcon />
        </div>
      )
    }
    

4. 验证类型配置

你的tsconfig.json和vite-env.d.ts配置是正确的,无需修改:

  • tsconfig.json中types数组包含vite-plugin-svgr/client
  • vite-env.d.ts中添加了/// <reference types="vite-plugin-svgr/client" />引用

5. 重启开发服务器

修改类型配置和插件配置后,必须重启Vite开发服务器,确保所有配置生效。

额外说明

如果需要给SVG组件添加自定义属性(比如title),vite-plugin-svgr的内置类型已经支持扩展SVG原生属性,无需额外声明。

内容的提问来源于stack exchange,提问作者Josh Silveous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 19:53:19