将PNG/SVG导入React - TS2307:找不到模块

3
在尝试将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;

我曾看到其他人遇到这个错误并尝试使用现有的解决方案(例如这个),比如在src文件夹中添加一个包含以下内容的.d.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",
    ]
}

非常感谢您的任何想法。


1
你的模块声明包含了 pngjpg 的定义。但是我在你的代码中没有看到 svg 模块的 TS 声明。 - Harshal Patil
1
忘记在问题中添加那行代码,但它在我的文件中。现在已经更新了问题。仍然不起作用。 - Saif
1
看起来你的 global.d.ts 没有被选中。 - Harshal Patil
1
我尝试过在tsconfig中重命名并显式添加到包含设置中,但没有成功。有什么想法吗? - Saif
1个回答

2
问题最终是由于我的tsconfig.json文件中的一个设置引起的(我不确定是哪个设置,因为我只是用create-react-app配置的输出替换了该文件)。请参见下面的新更新的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"
    ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接