Create-react-app: How can I import images from the public folder ?

Created on 24 May 2019  路  4Comments  路  Source: facebook/create-react-app

bug ?

css file

    background: url("./assets/bg.jpg") no-repeat;

error
Module not found: Can't resolve './assets/bg.jpg'

How do I set the path to a pure string

It doesn't have to be resolved

All 4 comments

Assuming that your assets folder if located directly inside the <project-root>/public folder, you do this:

- background: url("./assets/bg.jpg") no-repeat;
+ background: url("assets/bg.jpg") no-repeat;

CAUTION
This WILL NOT work in production environment if your website is not rooted in the public folder. What I mean is that if your website is being accessed as ***.domain.com/my-app, this assets won't be loaded because it will search for root of your website (which is root of ***.domain.com) and will try to load from their which may fail if you don't copy your assets to the root.

package.json

  "homepage": "."

Is there another way if I don't want to copy files manually ?

is there any way to set a pure string relative path ?

As far as I know, I don't think you will be able to load these assets (public/assets) if your project is served under a subdirectory.

If you can some how manage to move this background property from your css file to your inline css (in JS), then you can use process.env.PUBLIC_URL to add the background image like so:

<div style={{ background: `url(${process.env.PUBLIC_URL)/assets/bg.jpg` }}>

thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wereHamster picture wereHamster  路  3Comments

jnachtigall picture jnachtigall  路  3Comments

dualcnhq picture dualcnhq  路  3Comments

Aranir picture Aranir  路  3Comments

adrice727 picture adrice727  路  3Comments