问题描述
我正在尝试使用 TypeScript 导入要在 React 组件中使用的图像.我使用的打包器是 Parcel(不是 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
中.但是,当我尝试导入图像时,TS 对我大喊 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';
然后在 tsconfig.json
中添加 "include": ["./src/index.d.ts"]
,在 "compilerOptions" 之后:{...}
.
Then added "include": ["./src/index.d.ts"]
inside tsconfig.json
, after "compilerOptions" : {...}
.
我错过了什么?如何修复 TS 抛出的错误?
What did I miss? How can I fix the error TS is throwing?
推荐答案
如果你在 tsconfig 中直接写了
并且您没有 "include": ["./src/index.d.ts"]
.json"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 中导入图像 - “找不到模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2