[英]Typescript and React (with Gatsby loader): unable to import images as modules
First, I don't think Gatsby is involved in problem as runnning tsc -p .
首先,我不认为 Gatsby 与运行
tsc -p .
问题有关tsc -p .
will detect the same compilation errors, before gatby's yarn start
is ran.在运行gatby 的
yarn start
之前,将检测到相同的编译错误。
I have a folder with some react tsx files I want to compile我有一个文件夹,里面有一些我想编译的 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
I want bottom.tsx
to load email.png, but I have this error我想要
bottom.tsx
加载email.png,但我有这个错误
As written in this post , I declare all pictures as modules in src/@types/index.d.ts
. 正如这篇文章中所写,我将所有图片声明为
src/@types/index.d.ts
模块。 I have created a interface in this file for test urpose, and the file is correctly read by the compiler.我在这个文件中创建了一个接口用于测试目的,并且该文件被编译器正确读取。
declare module '*.jpg';
declare module '*.png';
export interface Thing {
name: string
}
Using import as or adding content to module declaration won't change anything.使用 import as 或向模块声明添加内容不会改变任何东西。 However the code is running fine if I ignore typescript compilator :
但是,如果我忽略打字稿编译器,代码运行良好:
//@ts-ignore
import email from '../../images/email.png'
//@ts-ignore
import logo from '../../images/logo-bw.png'
It works, so the structure of the code is ok with Gatsby, but obviously I lose a lot of benefits of using typescript as images is a big part of a website... Plus, there is no IDE autocompletion to help image import.它有效,所以 Gatsby 的代码结构没问题,但显然我失去了使用打字稿的很多好处,因为图像是网站的重要组成部分......另外,没有 IDE 自动完成来帮助图像导入。
This Gatsby starter is made to be open source, so you can check the configuration at this branch : https://github.com/robusta-code/gatsby-the-robust/tree/0.0.1这个 Gatsby starter 是开源的,所以你可以在这个分支检查配置: https : //github.com/robusta-code/gatsby-the-robust/tree/0.0.1
Note that loading css or sass modules would be ok : import '../styles/home.scss'
请注意,加载 css 或 sass 模块是可以的:
import '../styles/home.scss'
Wow... The problem is that my index.d.ts
was exporting an interface !哇...问题是我的
index.d.ts
正在导出一个接口!
In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.
在 TypeScript 中,就像在 ECMAScript 2015 中一样,任何包含顶级导入或导出的文件都被视为一个模块。 Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well)
相反,没有任何顶级导入或导出声明的文件被视为脚本,其内容在全局范围内可用(因此也对模块可用)
Removing export interface Thing{}
was enough.移除
export interface Thing{}
就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.