gpt4 book ai didi

Typescript 无法识别我的声明文件中声明的模块 (*.svg)

转载 作者:行者123 更新时间:2023-12-05 01:54:46 36 4
gpt4 key购买 nike

除其他声明外,我还在我的 ./src/types.d.ts 文件中声明了以下模块:

/// <reference types="@emotion/react/types/css-prop" />
import '@emotion/react';
import { PureComponent, SVGProps } from 'react';

declare module '*.svg' {
export class ReactComponent extends PureComponent<SVGProps<SVGSVGElement>> {}
}
declare module '*.ttf';
declare module '*.eot';
declare module '*.woff';
declare module '*.woff2';

当我运行 tsc --noEmit 错误时...

src/fonts/fonts.ts:39:31 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff' or its corresponding type declarations.

39 import PTSansregularWOFF from './pt-sans-v12-latin-ext_latin-regular.woff';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/fonts/fonts.ts:40:32 - error TS2307: Cannot find module './pt-sans-v12-latin-ext_latin-regular.woff2' or its corresponding type declarations.

40 import PTSansregularWOFF2 from './pt-sans-v12-latin-ext_latin-regular.woff2';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

src/layouts/default/NavigationBar.tsx:4:41 - error TS2307: Cannot find module '../../images/brand.svg' or its corresponding type declarations.

4 import { ReactComponent as Brand } from '../../images/brand.svg';
~~~~~~~~~~~~~~~~~~~~~~~~

……都吐出来了。

我的 tsconfig.json 看起来像这样:

{
"include": ["./src/**/*", "./.gatsby/**/*", "./*.ts", "./plugins/**/*"],
"files": ["./src/types.d.ts"],
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"lib": ["dom", "ES2017", "ES2019"],
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true,
"skipLibCheck": true,
"moduleResolution": "node",
"resolveJsonModule": true
}
}

我的文件树如下所示: File tree

如何让 Typescript 找到我对应的类型声明?

有趣的是,我的 types.d.ts 的其他部分也有影响,比如当我定义 @emotion/react 的接口(interface) Theme 时>.

最佳答案

我是这样使用的:

declare module '*.jpg';
declare module '*.png';
declare module '*.woff2';
declare module '*.woff';
declare module '*.ttf';

declare module '*.svg' {
import React = require('react');

export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}

然后像这样导入它:

import { ReactComponent as Logo } from './svg/logo.svg';
import SomeImage from './images/background.png';

关于Typescript 无法识别我的声明文件中声明的模块 (*.svg),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70554922/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com