try 导入PNG/SVG(或任何其他类型的图像!)TypeScript在我的React项目中引发以下错误:
TS2307: Cannot find module '../assets/images/homeHeroImage.svg' or its corresponding type declarations.
我正在为我的前端使用react、typescript和webpack,文件目录 struct 如下:
+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 suppress 错误,代码可以正常工作):
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;
我看到其他人也出现了这种错误,并try 使用现有的解决方案(如this one),例如添加.d、 src文件夹中的ts文件(在我的示例中为global.d.ts),其中包含以下内容:
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",
]
}
任何 idea 都将不胜感激.