如何使用Create React App和TypeScript将SVG导入组件?



我有一个用JS编写的React项目,我正在转换为TS.使用JS,这是有效的:

import { ReactComponent as IconPerson } from '../../../icons/person.svg';

使用TS,我得到这个错误:

找不到模块'../../../icons/person.svg'或其相应的类型声明。

我在新的索引中添加了以下内容。文件:

declare module '*.svg';

我还将index.d.ts文件添加到我的tsconfig.json中的include数组中:

{
include: ["src", "**/*.ts", "**/*.tsx", "index.d.ts"]
}

我错过了什么?

这个适合我:

declare module '*.svg' {
import React = require('react');
export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
}

信用:https://stackoverflow.com/a/54122106/2262604

创建ReactComponent变量对我来说似乎很奇怪,但我不再得到任何TS错误。