我正在尝试在使用TypeScript的React组件中导入图像。我使用的打包工具是Parcel(而不是Webpack)。
我在项目中创建了一个带有图像文件扩展名的 .d.ts
文件,并将其包含在 tsconfig.json
中。但是,当我尝试导入图像时,TS会抱怨找不到模块。
我的项目结构:
+ 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'
,并显示了 无法找到模块'../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';
然后在 "compilerOptions" : {...}
后面的 tsconfig.json
中添加 "include": ["./src/index.d.ts"]
。
我错过了什么?我该如何解决 TS 抛出的错误?
@types
包可以直接提供这些声明,这样我就不必自己明确地提供它们了? - Paul Razvan Berg@types
包可以直接提供这些声明,这样我就不必自己明确地提供它们了? - undefined