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 都将不胜感激.

推荐答案

问题原来是我的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"
    ]
}

Typescript相关问答推荐

对可变位置的父对象的TypScript空判断

如何让这个函数正确推断返回类型?

根据第一个参数的值设置第二个参数的类型

如何根据参数的值缩小函数内的签名范围?

net::BER_RECTION_REUSED和Uncatch使用Axios和TanStack-Query useMutation时未捕获错误(DelivercMutation)

如果存在ts—mock—imports,我们是否需要typescpt中的IoC容器

类型脚本强制泛型类型安全

在使用Typescribe时,是否有一种方法可以推断映射类型的键?

Redux—Toolkit查询仅在不为空的情况下添加参数

有没有办法解决这个问题,类型和IntrinsicAttributes类型没有相同的属性?

类型{}上不存在属性&STORE&A;-MobX&A;REACT&A;TYPE脚本

TypeScrip中的类型安全包装类

如何将父属性类型判断传播到子属性

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

如何解决&Quot;类型不可分配给TypeScrip IF语句中的类型&Quot;?

创建一个函数,该函数返回一个行为方式与传入函数相同的函数

如何在本地存储中声明该类型?

类型判断数组或对象的isEmpty

类型';只读<;部分<;字符串|记录<;字符串、字符串|未定义&>';上不存在TS 2339错误属性.属性&q;x&q;不存在字符串

有没有一种方法可以防止我的组件包在其中安装样式组件'; node 模块中的s目录