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:
add a directory called types on your project's root
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.
- install the file-loader dependence using npm, yarn or pnpm
npm install --save-dev file-loader
- 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)
Thanks @lukeshiru I agree with you!
after { test: / one '\' - not needed
@minompi, please make the change tot he example code to reflect this. Broken otherwise.
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 theextends
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...
Not gonna work for me I think:
./src/vite-env.d.ts
What a short and efficient article!
I just preferred to call the file
custom.d.ts
.Thanks