facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.77k stars 26.87k forks source link

How to set root for assets #2854

Closed mschipperheyn closed 7 years ago

mschipperheyn commented 7 years ago

I have my development directory like so

root
   public
     index.html
     images
        img1.png

However, on production, I don't use index.html. I deploy differently like so

root-file.php (here I put the root div and reference the main.xx.js file)
wp-content
    root
        public
           index.html
           images
              img1.png

I know, I know. WP, barf, barf. But it's what I have to deal with.

I need some way to flexibly use a hard reference for the images that I can switch easily for a production and development build because relative paths are not consistent between development and production. Any suggestions?

gaearon commented 7 years ago

You can do something like this. Set your homepage field in package.json to actual deployment address, e.g.

  "homepage": "http://mywebsite.com/wp-content/root/public/"

Note it doesn’t have to be called public. Although your source folder is called public, you’ll deploy the content of your build folder, and you can put it anywhere you like.

Then in the code you can do this:

const imgPath = `${process.env.PUBLIC_URL}/images/img1.png`;

This is mentioned in the documentation. It will become empty string in development, and the homepage path in production (e.g. /wp-content/root/public/ in our example).

Finally, you can avoid the whole problem altogether if you don’t use the public folder and instead import images inside the src folder.

import imgPath from './img1.png';

If you do this, the bundler will figure out to put them in correct place and set the right path.

Hope this helps!

mschipperheyn commented 7 years ago

Thx, I tried that and it didn't work for me.

I this solution: https://medium.com/@tacomanator/environments-with-create-react-app-7b645312c09d

adding a REACT_APP_SOMEVAR to the package.json

"start": "REACT_APP_ASSETS= react-scripts start",
"build": "REACT_APP_ASSETS=/wp-content/quiz react-scripts build",
<img src={`${process.env.REACT_APP_ASSETS}/images/img1.png`}/>
gaearon commented 7 years ago

This solution should work. If it doesn't there is either a bug or misunderstanding. But I can't tell which unless you provide more info about what exactly you tried, and how you determined it didn't work. I'm glad you found a workaround but next person that bumps into this issue will also be confused so it would be nice to get at the root of this.

mhluska commented 6 years ago

@gaearon this is not working for me either. Setting homepage in package.json and importing images from /src does not add the remote URL prefix. Mind you, I am testing with a .svg image.