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

新手上路,请多包涵

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

我在项目中创建了一个带有图像文件扩展名的 .d.ts 文件,并将其包含在 tsconfig.json 中。但是,当我尝试导入图像时,TS 对我大喊 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"] 里面 tsconfig.json ,之后 "compilerOptions" : {...}

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

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

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单个文件 ./src/index.d.ts 。当您在 VS Code 中打开任何其他文件时,VS Code 使用一个单独的语言服务实例,该实例不使用您的 tsconfig.json 。调整您的 "include" 设置以匹配项目中的所有 .ts.tsx 文件,或者只是删除它并依赖默认行为,即在包含 tsconfig.json 的目录。

第二轮

TypeScript is 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.将您的 index.d.ts 文件命名为其他名称,例如 declaration.d.ts

原文由 Matt McCutchen 发布,翻译遵循 CC BY-SA 4.0 许可协议

在文件夹中创建 index.d.ts 文件 src ,并添加这一行

declare module '*.jpg';

原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进