在React - TS2307中导入png / svg:找不到模块



当尝试将png/svg(或任何其他类型的图像)导入到我的React项目中时,TypeScript抛出以下错误:

TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations.

我使用react, typescript和webpack作为我的前端,文件目录结构如下:

+frontend
+src
+assets
+images
- homeHeroImage.svg
+components
- App.tsx
- Header.tsx
+home
- Home.tsx
- index.js
- global.d.ts
- package.json
- package-lock.json
- tsconfig.json
- webpack.config.js

下面是导入错误的代码(我可以用@ts-ignore来抑制错误,代码可以工作):

import React from "react";
import Header from "../Header";
import HomeHeroImage from "../../assets/images/homeHeroImage.svg";
const Home = () => <Header headingText="Heading text" slogan="A slogan" imagePath={HomeHeroImage}/>;
export default Home;

我看到这个错误发生在其他人身上,并试图使用现有的解决方案(像这个),比如添加。d。Ts文件(在我的例子中是global. d.s Ts)在SRC文件夹中,其中包含以下内容:

declare module "*.png";
declare module "*.svg";
declare module "*.jpg";

然而,这对我不起作用。作为参考,下面是我的tsconfig的内容。json文件:

{
"compilerOptions": {
"target": "ES5",
"module": "ESNext",
"moduleResolution": "node",
"jsx": "react-jsx",
"noEmit": true,
"isolatedModules": true,
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"baseUrl": "frontend/src",
},
"files": ["frontend/src/*"],
"include": [
"frontend/src/*",
"frontend/src/global.d.ts",
]
}

如有任何意见,不胜感激。

问题原来是我的tsconfig中的设置。json文件(我不确定是哪一个,因为我只是用create-react-app configs的输出替换了文件)。请参阅新更新的tsconfig。下面的Json文件解决了这个问题:

{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"frontend/src"
]
}

最新更新