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.
To reference assets in the public folder, you need to use an environment variable called PUBLIC_URL . Only files inside the public folder will be accessible by %PUBLIC_URL% prefix.
Usage is simple — you insert the path to the image you want to include in your page inside the brackets of url() , for example: background-image: url('images/my-image. png');
export default App; Output: Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image. In this file, we will import the image and set it as a background image of the div element.
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
you can import that image as
import Background from './Screenshot_11.png'
and use
background-image: `url(${Background})`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With