Raihan Rahman
Raihan Rahman

Reputation: 45

React CSS can't use image from public

I create a project with create-react-app project_name, and then I tried to use a image from public folder as background with this code in css background-image: url('/images/ernestDrum.jpeg');

and then I got this error ./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/ernestDrum.jpeg' in 'E:\project\ernest\src' in my previous project, I use the same code and it's works

Upvotes: 0

Views: 4460

Answers (2)

Dragonite
Dragonite

Reputation: 34

I got same error after updating react-scipts from 3.x.x to 4.x.x
and found this issue https://github.com/facebook/create-react-app/issues/9870

Roll back to 3.x.x can solve this problem

Upvotes: 1

JBallin
JBallin

Reputation: 9817

CRA Docs - Using the Public Folder:

...we normally encourage you to import assets in JavaScript files instead.

CRA Docs - Adding Images, Fonts, and Files:

You can import a file right in a JavaScript module.

CRA does provide a way to use the public folder (1st link), but I would instead recommend placing images directly in /src (you could still use an /images folder). CRA's webpack set up will handle the rest. Note that you'll want to use a relative import:

background-image: url('./images/ernestDrum.jpeg');

Upvotes: 2

Related Questions