在TypeScript React中导入图像-“找不到模块" [英] Importing images in TypeScript React - "Cannot find module"

查看:1283
本文介绍了在TypeScript React中导入图像-“找不到模块"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试导入图像以在带有TypeScript的React组件中使用.我正在使用的捆绑器是包裹(不是Webpack).

I am trying to import images to use inside a React component with TypeScript. The bundler I'm using is Parcel (not Webpack).

我已经在项目内部创建了具有图像文件扩展名的.d.ts文件,并将其包含在tsconfig.json中.但是,当我尝试导入图像时,T​​S对Cannot find module吼叫我.

I have created a .d.ts file inside the project with the image file extension, and included it inside tsconfig.json. However, when I try to import an image, TS yells at me about Cannot find module.

我的项目结构:

+ src
  + assets
    - image.jpg
  + components
    - Box.tsx
    - App.tsx
  - index.d.ts
  - index.html
  - index.tsx
- tsconfig.json
- tslint.json

我试图像这样在App.tsx中导入图像. VS Code在'../assets/image.jpg'下划线并表示Cannot find module '../assets/image.jpg'.

I tried to import the image in App.tsx like this. VS Code underlined '../assets/image.jpg' and said Cannot find module '../assets/image.jpg'.

import * as React from 'react';
import * as img from '../assets/image.jpg';

const Box = props => {
  // do things...
}

export default Box;

我在网上找到的讨论都指向我自己定义.d.ts文件的需要,因此我在这一行中创建了该index.d.ts文件.

The discussions I found online point to the need of defining a .d.ts file myself, so I created that index.d.ts file with this line.

declare module '*.jpg';

然后在"compilerOptions" : {...}之后在tsconfig.json内添加"include": ["./src/index.d.ts"].

我想念什么?如何解决TS抛出的错误?

What did I miss? How can I fix the error TS is throwing?

推荐答案

如果您在tsconfig.json中确实编写了"include": ["./src/index.d.ts"],并且没有"files"设置,则表示由tsconfig.json定义的项目包括仅单个文件./src/index.d.ts.当您在VS Code中打开任何其他文件时,VS Code使用一个单独的语言服务实例,该实例不使用您的tsconfig.json.调整"include"设置以匹配项目中的所有.ts.tsx文件,或者只是将其删除并依靠默认行为,即将所有文件包含在包含tsconfig.json的目录下.

If you literally wrote "include": ["./src/index.d.ts"] in tsconfig.json and you don't have a "files" setting, that means the project defined by tsconfig.json includes only the single file ./src/index.d.ts. When you open any other file in VS Code, VS Code uses a separate language service instance that doesn't use your tsconfig.json. Adjust your "include" setting to match all the .ts and .tsx files in your project, or just delete it and rely on the default behavior of including all files under the directory containing tsconfig.json.

TypeScript忽略了index.d.ts,因为它假定index.d.ts是从index.tsx生成的,并且index.tsx更可能是最新的.将您的index.d.ts文件命名为其他名称,例如declaration.d.ts.

TypeScript is ignoring index.d.ts because it assumes that index.d.ts is generated from index.tsx and index.tsx is more likely to be up to date. Name your index.d.ts file something else, e.g., declaration.d.ts.

这篇关于在TypeScript React中导入图像-“找不到模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆