javascriptcreate-react-appdevelopment-environmentproductionfile-access

Access files in public directory after production (create-react-app)


I've been working in Create-react-app and had a development build I was ready to publish. I ran commands such as seen here and was successful in deploying to GitHub pages. After deploying, I went back to make some changes and files in my 'public' directory were no longer showing in development (I used npm start to get back to development, which is perhaps a source of the issue).

I have some images in the 'public' directory I was accessing from the 'src' directory (I understand that's not generally recommended, but it aligns with some practice problems I'm doing through a course). The file path worked fine in both development and production. But when I went back to development, I seem to be in a different version of development. Below are some snapshots of my file path to hopefully clarify:

  1. File path on my computer. From src/components/TravelCard.js, I need to access items in public/images/. It worked fine in development and production with <img src={`./images/${props.img.tripPic}`} alt=""/>

    My file path on my computer.

  2. File path shown in Chrome Dev Tools before production (note this is from a similar project since I can't get back to it from the current project).

    working file path in development

  3. File path shown in Chrome Dev Tools after production when accessed using npm start.

    broken file path in development after production

I'm happy to explain more if this doesn't provide enough information. My repo is here. Thanks for any assistance.


Solution

  • EDIT: I was totally wrong. Here's the correct answer for create-react-app projects:

    <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

    https://create-react-app.dev/docs/using-the-public-folder/#adding-assets-outside-of-the-module-system


    (old answer)

    No ., just /images/rest/of/file/path.