Create-react-app: CRA 4 fails to compile when css background-image ulr('url') not resolved

Created on 5 Nov 2020  路  6Comments  路  Source: facebook/create-react-app

I have a css file that is imported in my react app, it is something like:

styles.css

.flag { ... background-image: url("/img/flags.png") !important; }

It is imported in my react file -> import './styles.css';

In the previous version of CRA it works well, and when I build the app it was also okay, since I have the /img/flags.png in my 'public' directory.

After CRA 4 it fails to compile

Best regards

bug report needs triage

Most helpful comment

I'm surprised this isn't a show stopper for more people. Any light on a work around or approach I'm not getting would be helpful.

Cheers!

All 6 comments

This guide still works: https://create-react-app.dev/docs/adding-images-fonts-and-files

You should not link to the public folder in your src or css. Create a static directory in your src folder and do like:

background-image: url("./static/img/flags.png");

@pascalstr, Your solution works, but I have to move all the assets that do not need to be in the src folder, such as images, videos, fonts, and so on. Also, all of these will beside together in the media folder that CRA created by default and is not customized for production.

@pascalstr Thanks that works for me!

@Saeed-Rohani #9937 seems to be a similar issue, maybe close this in favour of #9973

This guide still works: https://create-react-app.dev/docs/adding-images-fonts-and-files

You should not link to the public folder in your src or css. Create a static directory in your src folder and do like:

background-image: url("./static/img/flags.png");

@Saeed-Rohani The guide makes sense but how would you reference an image in an inline style to do something like this:

style={{backgroundImage:"url(/img/example.png)"}}

in this case static will not work and the use case being...

style={{backgroundImage:"url(/img/example-"+var+".png)"}}

Cheers

I'm surprised this isn't a show stopper for more people. Any light on a work around or approach I'm not getting would be helpful.

Cheers!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rdamian3 picture rdamian3  路  3Comments

barcher picture barcher  路  3Comments

DaveLindberg picture DaveLindberg  路  3Comments

AlexeyRyashencev picture AlexeyRyashencev  路  3Comments

alleroux picture alleroux  路  3Comments