Cannot find module '@/assets/images/icon.png' or its corresponding type declarations.

April 18, 2024 2:46 PM

React JS Importing Asset in ReactJS

Recently, I was working on a React project with typescript, where I was trying to import a image file from asset directory. Well, the code was working well in the browser but I was seeing alert for the import stating that "Cannot find module '@/assets/images/icon.png' or its corresponding type declarations". The fun part was everything was working fine on the browser but I was not happy with this alert for this image import.


So I was trying to figure out why my typescript is little unhappy with this import.

The error I was encountering typically occurs when TypeScript is unable to locate the module for the image or its type declarations. This can happen because TypeScript, by default, doesn't know how to handle non-code assets like images. Here's how we can resolve this issue:

  1. Create a declaration file for image modules: You need to tell TypeScript how to handle imports for image files. You can do this by declaring a module for image files.

Create a new file named custom.d.ts in your project (you can place it in your src directory or a types directory if you have one). Then, add the following content:

declare module "*.png" {
  const value: string;
  export default value;
}

This code tells TypeScript that when it encounters an import statement for a .png file, it should treat it as a module that exports a string (the URL to the image).


  1. Ensure your tsconfig.json includes the declaration file: Make sure that the tsconfig.json file in your project is configured to include the custom.d.ts file you just created. If your tsconfig.json has an include array, add the path to your declaration file to this array. If there's no include array, TypeScript will include all .ts, .tsx, and .d.ts files in your project by default, as long as they are not excluded in the exclude array.

Here's an example of what your tsconfig.json might look like with the include array:

{
  "compilerOptions": {
    // compiler options...
  },
  "include": ["src/**/*", "src/custom.d.ts"]
}


After making these changes, restart our TypeScript server in your IDE (if you're using VS Code, you can do this by opening the command palette and running the "TypeScript: Restart TS server" command) or restart our development server if necessary.

This should resolve the error and allow us to import images without TypeScript errors.

Comments


    Read next