我正在尝试使用 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 抛出的错误?