在 TypeScript React 中导入图像 - “找不到模块”

2023-12-11

我正在尝试导入图像以在带有 TypeScript 的 React 组件中使用。我使用的打包器是 Parcel (不是 Webpack)。

我创建了一个.d.ts文件内的图像文件扩展名,并将其包含在里面tsconfig.json。然而,当我尝试导入图像时,T​​S 对我大喊大叫: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'.

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文件与这一行。

declare module '*.jpg';

然后添加"include": ["./src/index.d.ts"] inside tsconfig.json, after "compilerOptions" : {...}.

我错过了什么?如何修复 TS 抛出的错误?


create index.d.ts文件夹中的文件src,并添加这一行

declare module '*.jpg';
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 TypeScript React 中导入图像 - “找不到模块” 的相关文章

随机推荐