简体   繁体   中英

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 . will detect the same compilation errors, before gatby's yarn start is ran.

I have a folder with some react tsx files I want to compile

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

TS2307:无法加载图像模块

As written in this post , I declare all pictures as modules in 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. 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.

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

Note that loading css or sass modules would be ok : import '../styles/home.scss'

Wow... The problem is that my index.d.ts was exporting an interface !

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM