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

import logo from './logo.svg';

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

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

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


当前回答

    // eslint-disable-next-line spaced-comment
/// <reference types="react-scripts" />

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

其他回答

如果没有其他的答案工作,尝试重新启动你的IDE(即VS Code)。对我来说,这就解决了问题。

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

看到源

如果你正在使用Create-React-App启动器,请确保react-app-env.d。Ts包含如下行:

/// <reference types="react-scripts" />

如果你使用webpack,安装svg-inline-loader,在webpack.config.js中添加该模块:

{
    test: /\.svg$/,
    loader: 'svg-inline-loader',
}

它在建造后工作良好。

如果你的IDE报告一个交互错误,它可以通过添加//@ts-ignore来解决:

//@ts-ignore
import logo from './logo.svg';

Svg-inline-loader webpack文档

    // eslint-disable-next-line spaced-comment
/// <reference types="react-scripts" />

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