14

Here is my code i am trying to add image but its shows error

background-image: url('/images/img-2.jpg');

Failed to compile.

./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css)
Error: Can't resolve '/images/img-2.jpg' in 'E:\React\react-demo\src'
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
Avinash gupta
  • 181
  • 1
  • 2
  • 7

4 Answers4

17

Because you asked for an image not founded in the src folder! maybe you're trying to access the images in the public folder at your React project.

My Friend's life is easy, React - using Webpack - converts the jpg/png..etc images to base64 then replaces the URL to the base64... like this

enter image description here

So, you need to make an assets/images folder inside the src folder that contains all your images, then import the link in your CSS

  background-image: url("./assets/images/logo512.png");

Again, React will convert the image to bases64! That will make the image not depend on the folder Path.

Tawfeeq Amro
  • 605
  • 7
  • 15
3

I got myself in a similar situation. Here's the fix I made: The error is saying that you do not have an image under src

simply move the image under src then redirect the URL to it

background: url('/src/images/img-2.jpg');
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
acmatias
  • 31
  • 1
3

Module not found: Error: Can't resolve '/images/img-2.jpg'

Add your images to your src ... pretty much move it from public to the src folder

background-image: url('/src/images/img-2.jpg');
drcode
  • 31
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 02 '22 at 08:29
  • The answer could also be like below, background-image: url('@/assets/images/img-2.jpg'); // if your src folder is `assets`. i mean where you have kept your css, scss, images etc static folder. So, you have to keep in mind that where is my static folder. Just add `@` icon then `/` and then the main source folder then then image path. – miltonbhowmick Apr 04 '22 at 04:21
0

*By setting the URL path to /image.png like the example above, the browser will look for the background image at /image.png.

You can also create another folder inside public/ if you want to organize your images into folders.*

<div style={{ backgroundImage: "url(/image.png)}}>
  Hello World
</div>
Gouda P
  • 126
  • 8