Typescript 和 React(使用 Gatsby 加载器):无法将图像作为模块导入

Nic*_*zol 5 typescript reactjs gatsby

首先,我不认为 Gatsby 与问题有关,因为tsc -p .yarn start运行gatby 之前,runnning会检测到相同的编译错误。

我有一个文件夹,里面有一些我想编译的 react tsx 文件

src/
  @types/
    index.d.ts
  components/
    bottom/bottom.tsx
    layout.tsx
  images/
    email.png
    costs.png 
gatsby-config.js
gatsby-node.js
tsconfig.json
package.json
Run Code Online (Sandbox Code Playgroud)

我想bottom.tsx加载 email.png,但出现此错误

TS2307:无法加载图像模块

正如这篇文章中所写,我将所有图片声明为src/@types/index.d.ts. 我在这个文件中创建了一个接口用于测试目的,并且该文件被编译器正确读取。

declare module '*.jpg';
declare module '*.png';?

export interface Thing {
    name: string
}
Run Code Online (Sandbox Code Playgroud)

使用 import as 或向模块声明添加内容不会改变任何东西。但是,如果我忽略打字稿编译器,代码运行良好:

//@ts-ignore
import email from '../../images/email.png'
//@ts-ignore
import logo from '../../images/logo-bw.png'
Run Code Online (Sandbox Code Playgroud)

它有效,所以 Gatsby 的代码结构没问题,但显然我失去了使用打字稿的很多好处,因为图像是网站的重要组成部分......另外,没有 IDE 自动完成来帮助图像导入。

这个 Gatsby starter 是开源的,所以你可以在这个分支检查配置:https : //github.com/robusta-code/gatsby-the-robust/tree/0.0.1

请注意,加载 css 或 sass 模块是可以的: import '../styles/home.scss'

Nic*_*zol 3

哇...问题是我index.d.ts正在导出一个接口!

在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被视为模块。相反,没有任何顶级导入或导出声明的文件被视为其内容在全局范围内可用的脚本(因此也适用于模块)

删除export interface Thing{}就足够了。