Home > database >  Importing PNGs/SVGs into React - TS2307: Cannot find module
Importing PNGs/SVGs into React - TS2307: Cannot find module

Time:06-17

When trying to import PNGs/SVGs (or any other kind of image for that matter!) into my React project, TypeScript throws the following error:

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

I am using react, typescript and webpack for my frontend with the below file directory structure:

 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

Below is the code with the import error (I can suppress the error with @ts-ignore and the code works):

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;

I have seen this error occur for other people and tried to use existing solutions (like this one) such as adding a .d.ts file (in my case, global.d.ts) in the src folder which contains the below:

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

However, this didn't work for me. For reference below is the contents of my tsconfig.json file:

{
    "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",
    ]
}

Any ideas would be much appreciated.

CodePudding user response:

The issue turned out to be a setting in my tsconfig.json file (I'm not sure which one as I just replaced the file with the output of create-react-app configs). See the new updated tsconfig.json file below which solved the problem:

{
"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"
    ]
}
  • Related