Freestyle09
Freestyle09

Reputation: 5528

React path to public folder in css background image

I am using Create-React-App and I want to add background image for my header section and I am doing this in that way:

background-image: url('~/Screenshot_11.png');

After this I'm getting this error:

./src/styles/main.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/sass-loader/lib/loader.js??ref--6-oneOf-5-3!./src/styles/main.scss) Module not found: You attempted to import ../../../../../../../Screenshot_11.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

I've set up homepage in package.json

"homepage": "http://localhost:3000",

In my older projects that works but today I cannot import this correctly.

Upvotes: 36

Views: 62846

Answers (3)

zpetukhov
zpetukhov

Reputation: 141

This still does not work for me with images in the public folder.

UPDATED 19 March 2021

Regarding using of <ROOT/public/images> in .css files.

It appears to be a breaking change (will be considered as a bug?) in create-react-app (react-scripts) package v4.x.
And more precisely in package 'css-loader' v4.x.
3.x branch works OK with that.

Here is the corresponding issue on the github repo:
https://github.com/facebook/create-react-app/issues/9870
(and there are few more actually).

No fixes (yet). (will be?..)
But a few workarounds mentioned there. Which one to use... it depends on your project, I suppose.

Some of workarounds:

  • downgrade to react-scripts 3.4.x

  • don't use url in CSS files :) you still can use in .JSX (inline styles). Or put in .html. They are obviously not processed by css-loader.

  • reconfigure webpack to add url:false to css-loader options (either eject CRA or use this: https://github.com/gsoft-inc/craco or this: https://github.com/timarney/react-app-rewired (you can find sample configurations at the github issue page)

  • use this new feature of css-loader https://github.com/webpack-contrib/css-loader/pull/1264 (released in 5.1.0, current last version is 5.1.3; to use that version you can add the following to the package.json: "resolutions": { "css-loader": "5.1.3" } (at root level) )

Upvotes: 11

Freestyle09
Freestyle09

Reputation: 5528

They have changed that but I don't know why. Working path:

background-image: url('/Screenshot_11.png');

EDIT 2021

For people who think that it doesn't work:

https://codesandbox.io/s/agitated-turing-gsnr3

Upvotes: 32

Sabesan
Sabesan

Reputation: 712

you can import that image as

import Background from './Screenshot_11.png'

and use

background-image: `url(${Background})`

Upvotes: 18

Related Questions