Add images to a React project with Typescript (2024)

Add images to a React project with Typescript (1)

AlessandroMinoccheri

Posted on • Originally published at minompi.Medium

Add images to a React project with Typescript (3) Add images to a React project with Typescript (4) Add images to a React project with Typescript (5) Add images to a React project with Typescript (6) Add images to a React project with Typescript (7)

#react #javascript #typescript #webpack

In every single project, usually, you need to add an image to your React project to show something or to represent a graph and create a beautiful page for your audience.

Adding an image with React is very simple and fast, this is an example:

import React from "react";import imageToAdd from "./../assets/images/logo.png";function YourComponent() { return <img src={imageToAdd} alt="Image" />;}export default YourComponent;

This works like a charm in a React project built using CRA or Vite.
but if your project has a custom bundler, created using Typescript + Webpack, with the code above you will receive this error:

Cannot find module './../assets/images/logo.png'

The first time I saw that error, I thought “It’s a bug!”, but after searching and understanding typescript well, I discovered that receiving an error is the correct behavior.

By default in typescript, the module resolution resolves the import using only the files with extension: .ts .tsx or .d.ts and this is the reason why in the previous case the module couldn't be found.

So, how can we fix the problem?
To solve the problem, usually, you have to:

  1. add a directory called types on your project's root

  2. create inside of that folder a file called index.d.ts with the following content

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

N.B. the extension depends on the file type you are adding.

  1. install the file-loader dependence using npm, yarn or pnpm
npm install --save-dev file-loader

  1. update your webpack config file to use the file-loader module like this
...{ test: /\\.(png|jp(e*)g|svg|gif)$/, use: ['file-loader'], }...

Then, you can run your application, your build will succeed and your image will appear! 🎩

Top comments (6)

Subscribe

AlessandroMinoccheri

AlessandroMinoccheri

Software developer @FlowingYou can follow me on Twitter @minompi

  • Email

    alessandro.minoccheri@gmail.com

  • Location

    Italy

  • Work

    Senior software developer

  • Joined

Jul 23 '22

  • Copy link

Thanks @lukeshiru I agree with you!

cho

cho

  • Joined

Nov 21 '22

  • Copy link

after { test: / one '\' - not needed

Sean Frisbey

  • Joined

Apr 19 '23

  • Copy link

@minompi, please make the change tot he example code to reflect this. Broken otherwise.

Mohammad Jawad (Kasir) Barati

Mohammad Jawad (Kasir) Barati

A Fullstack dev with love for cutting edge technologies and on his journey to learn and teach. Having a can-do attitude and being industrious gave me the courage to question the status quo.

  • Email

    node.js.developers.kh@gmail.com

  • Location

    Bremen, Germany

  • Education

    Bachelor

  • Pronouns

    He/Him/His

  • Work

    Fullstack Engineer

  • Joined

May 16 '23 • Edited on May 16 • Edited

  • Copy link

Thanks. I found the issue. In my Vite project I was extending another tsconfig in my main tsconfig - something like this: "extends": "../../tsconfig.json" and IDK why but then TSC was confused and could not find image files. After removing the extends it just came to its senses and worked. Do you have any idea on what was wrong with it?

Here you can see what I meant: github.com/kasir-barati/ts-boilerp...

Mohammad Jawad (Kasir) Barati

Mohammad Jawad (Kasir) Barati

A Fullstack dev with love for cutting edge technologies and on his journey to learn and teach. Having a can-do attitude and being industrious gave me the courage to question the status quo.

  • Email

    node.js.developers.kh@gmail.com

  • Location

    Bremen, Germany

  • Education

    Bachelor

  • Pronouns

    He/Him/His

  • Work

    Fullstack Engineer

  • Joined

May 3 '23

  • Copy link

Not gonna work for me I think:

Duplicate identifier 'path'.ts(2300)client.d.ts(107, 18): 'path' was also declared here.client.d.ts(111, 18): and here.client.d.ts(131, 18): and here.client.d.ts(103, 18): and here.

./src/vite-env.d.ts

/// <reference types="vite/client" />declare module '*.jpg' { const path: string; export default path;}declare module '*.jpeg' { const path: string; export default path;}declare module '*.svg' { const path: string; export default path;}declare module '*.png' { const path: string; export default path;}

Tamires Cordeiro

Tamires Cordeiro

Programadora e comunicadora envolvida em projetos que unam desenvolvimento, design e edição.

  • Joined

Dec 2 '22

  • Copy link

What a short and efficient article!
I just preferred to call the file custom.d.ts.
Thanks

For further actions, you may consider blocking this person and/or reporting abuse

Add images to a React project with Typescript (2024)
Top Articles
Decoding PayPal Holdings Inc (PYPL): A Strategic SWOT Insight
Tesla formally drops FSD “Beta” moniker, replaces it with FSD (Supervised)
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 6213

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.