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

无需?react导入SVG组件时Vite无法识别Prop类型的问题咨询

无需?react后缀导入SVG组件及Props类型支持解决方案

问题背景

当前vite-plugin-svgr配置如下:

export default defineConfig({
    plugins: [
        paths(),
        svgr({
            include: '**/*.svg',
        }),
        react({
            plugins: [['@swc/plugin-emotion', {}]],
            jsxImportSource: '@emotion/react',
        }),
    ],
});

已实现无需添加?react后缀即可导入SVG作为组件使用,组件能正常渲染,但传入属性(如fill="#111")时出现类型错误:

Type '{ fill: string; }' is not assignable to type 'IntrinsicAttributes'.

相关依赖版本:

"vite": "6.0.11",
"vite-plugin-svgr": "4.3.0",
"react": "18.3.1",
"@types/react": "18.3.18",

当前vite-env.d.ts内容:

/// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />

可行方案及类型修复步骤

完全可以实现无?react后缀导入SVG组件,类型问题可通过自定义TypeScript类型声明解决:

  1. 创建自定义SVG类型声明文件
    在项目的类型目录(如src/types/)下新建svg.d.ts文件,内容如下:
declare module '*.svg' {
  import type React from 'react';
  const SVGComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  export default SVGComponent;
}

该声明会将所有.svg文件的导出类型定义为React函数组件,并继承SVG元素的所有Props类型(包括fill、width、height等)。

  1. 调整类型引用优先级
    修改vite-env.d.ts,移除原有的vite-plugin-svgr/client类型引用(避免与自定义类型冲突),最终内容:
/// <reference types="vite/client" />
/// <reference path="./src/types/svg.d.ts" />

如果你的类型文件路径不同,需对应调整path值。

  1. 验证TypeScript配置
    确保tsconfig.json的include字段包含自定义类型文件所在目录,例如:
{
  "include": ["src/**/*", "src/types/**/*.d.ts"]
}

完成以上步骤后,导入的SVG组件就能获得完整的Props类型支持,传入fill等属性时不会再出现类型错误。

内容的提问来源于stack exchange,提问作者Богдан Баталов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 13:31:09