DEV Community

Yuya Hirano
Yuya Hirano

Posted on

Resolve error that occur when importing image file in React with TypeScript

Overview

When using TypeScript on React, an error occur when trying to import an image.
So, fix the error that occurs when importing images in React.

What should I do ?

Create a type definition for the image to be used


#1 Install React with TypeScript

npx create-react-app my-app --template typescript
Enter fullscreen mode Exit fullscreen mode

#2 Directory structure

Image description

#3 Place the image to be used

Image description

#4 Create a type definition

Image description

declare module "*.jpg";
Enter fullscreen mode Exit fullscreen mode

#5 import type definition file

import "./App.css";
import "./types/image.d.ts";
import sample_image from "./assets/sample.jpg";

function App() {
  return <img src={sample_image} alt="sample"/>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode




done.

Top comments (0)