在TypeScript React中导入图像-“找不到模块" [英] Importing images in TypeScript React - "Cannot find module"
问题描述
我正在尝试导入图像以在带有TypeScript的React组件中使用.我正在使用的捆绑器是包裹(不是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';
然后在"compilerOptions" : {...}
之后在tsconfig.json
内添加"include": ["./src/index.d.ts"]
.
我想念什么?如何解决TS抛出的错误?
What did I miss? How can I fix the error TS is throwing?
推荐答案
如果您在tsconfig.json
中确实编写了"include": ["./src/index.d.ts"]
,并且没有"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中导入图像-“找不到模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!