react svg 导入错误

这篇文章发表于 阅读 0

react组件中import svg文件时出现如下报错:

error TS2307: Cannot find module 'icon.svg' or its corresponding type declarations.

这有由于没有找到svg文件的声明,可以用如下方法解决。

解决方式

第1种:

在global.d.ts中添加

declare module "*.svg" { const content: any; export default content; }

第二种:

在global.d.ts中添加

declare module '*.svg' { import React from 'react'; export const ReactComponent: React.FunctionComponent<React.SVGProps< SVGSVGElement > & { title?: string }>; const src: string; export default src; }

第三种:

如果上面都没解决问题,那么可以直接将svg转成react组件。

import React from "react"; const Icon = (): JSX.Element => ( <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 1024 1024"> <path d="xxxxxxx"></path> </svg> ); export default Icon;