在typescript(*.tsx)文件中,我不能用下面的语句导入svg文件:

import logo from './logo.svg';

Transpiler说:[ts]找不到模块'./logo.svg'。 我的svg文件就是<svg>…</svg>。

但在.js文件中,我能够导入它没有任何问题,完全相同的导入语句。我想这与svg文件的类型有关,它必须以某种方式为ts transpiler设置。

你能在ts文件中分享一下如何做到这一点吗?


当前回答

你可以像create-react-app一样为svgs声明module:

react-app.d.ts

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

看到源

其他回答

感谢smarx指出使用require()。所以在我的例子中,它应该是:

const logo = require("./logo.svg") as string;

在*中工作得很好。tsx文件

我在网上寻找解决这个问题的办法。这个stackoverflow问题是最重要的,但没有一个答案对我有用。

最后,我通过尝试一些不同的技术找到了解决方案。

创建一个。/global .d。Ts文件在你的项目的根目录,在你的。/tsconfig文件的同一位置/级别。json。 在。/globals.d中。Ts文件,添加这个:

declare module '*.svg' {
  const content: string;
  export default content;
}

这正确地将.svg导入为字符串,这是我在排名最高的答案中注意到的一个问题。

更新您的tsconfig。Json格式:

{
  "files": ["globals.d.ts"]
}

就是这样,这对我来说很管用。这是一个VanillaJS应用。

找不到模块或对应的类型声明|无法在typescript中导入svg文件

在。/custom.d中。Ts文件,添加这个:

declare module '*.svg' {
  const content: string;
  export default content;
}

如果你有任何困惑,请观看这个视频。 https://www.youtube.com/watch?v=Skhgdp7R9Tk

对我来说,当我在src/types/images.d.ts中放入以下一行时,它就工作了

声明模块'*.svg';

我用下面的方法导入图像

import {ReactComponent as WifiIcon} from '../../ assets/images/Wifi.svg';

在tsconfig.json

我有以下complierOptions

"compilerOptions": {
    "typeRoots": ["node_modules/@types", "src/types"]
}

希望它能帮助到别人。我使用的是最新版本的CRA。

你可以像create-react-app一样为svgs声明module:

react-app.d.ts

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

看到源