Intro..
The above errors often occurred when importing images or files using TypeScript.
This post is about TS error resolution.
Error
[Typescript] TS2307: Cannot find module '.png' or its corresponding type declarations.
While starting a new project with React and TypeScript, I tried to import an image file with a .png extension name, but the error appeared, so it didn't work.
When I searched and looked it up, it was because the type was not defined.
1// tsconfig.json 2... 3"typeRoots": ["src/types"], 4...
I added the .d.ts file to the src/types folder to add the type.
The image could be imported successfully.
1// src/types/images.d.ts 2declare module '*.png'; 3declare module '*.jpg'; 4declare module '*.jpeg';
Of course, there are other ways.
We can also use the type in more detail to declare each extension of the image.
1declare module "*.svg" { 2 import * as React from "react"; 3 4 export const ReactComponent: React.FuncctionComponent< 5 React.SVGProps<SVGVGElement> & {title?: string } 6 >; 7 8 const src: string; 9 export default src; 10} 11 12declare module "*.png" { 13 const png: string; 14 export default png; 15}
Both of the above examples work fine as normal.
π‘ If the error persists after declaring each extension in the d.ts file as above, try turning off and on the vsCode.



