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

import logo from './logo.svg';

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

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

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


当前回答

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

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

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

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

其他回答

没有webpack和custom.d.ts的解决方案

对我来说,上面的解决方案单独一个都不起作用。因为我在目前的项目中没有使用Webpack。

我研究了日志中的输出,然后使用以下方式,无需创建文件(custom.d.ts),更改配置或安装新的依赖项:

const logo: string = require("../assets/images/logo.svg").default;

<img src={logo} alt="logo" />

对于svg格式,您需要添加.default,但对于png格式则不需要。

对我来说,我必须包含react-app-env.d。tsconfig*.json:

  "include": [
    "src/Router.tsx",        // my main entry point
    "src/global.d.ts",       // global stuff
    "src/react-app-env.d.ts" // react global stuff
  ]
    // eslint-disable-next-line spaced-comment
/// <reference types="react-scripts" />

如果你正在使用puglin slint,可能是他已经禁用了,认为这是一个评论,但不是为了阅读SVG,你需要这个类型脚本模块,只是禁用行和高兴

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

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

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

你可以像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;
}

看到源