2

I have a react app with this project structure:

enter image description here

In my Home component and About component I have two images With src set to : <img src="/img/charlie1.jpg" alt="charlie home pic" /> and <img src="/img/charlie2.jpg" alt="charlie about pic" />

So I assume it will start looking in the root folder then the image folder then find the pictures in there.

This works fine when I’m developing on my local machine The images will display correctly.

But when I build it and move the files to prod the images won’t work It looks for the image at this path: https://xyz.github.io/img/charlie2.jpg instead of https://xyz.github.io/charlieReact/img/charlie2.jpg

How can I fix this problem?

If I change the image src to : <img src="./img/charlie1.jpg" alt="charlie home pic" />

Then it works in github pages, but then the images won’t display when I’m on my local machine…

3
  • May I ask why you don't want to import the images in the JavaScript, i.e. import charlie1 from './charlie1.jpg'? Do you have too many images? Maybe this could work. Commented Nov 9, 2018 at 22:01
  • Ah! that worked. Is that how it should be done? Commented Nov 9, 2018 at 22:08
  • 1
    It's a good idea to import the images into the JavaScript and use the imported variable whenever you can, and the URLs will just work by themselves. If your page has a root other than / and you have assets in the public directory, you most likely have to do some extra logic in the code. Commented Nov 9, 2018 at 22:12

2 Answers 2

1

It's a good idea to import the images into the JavaScript and use the imported variable whenever you can, and the URLs will just work by themselves.

import charlie1 from './charlie1.jpg';

<img src={charlie1} />

If your page has a root other than / and you have assets in the public directory, you most likely have to do some extra logic in the code.

package.json

{
  "homepage": "https://xyz.github.io/charlieReact"
}

App.js

<img src={`${process.env.PUBLIC_URL}/img/charlie1.jpg`} />
Sign up to request clarification or add additional context in comments.

Comments

0

In my case I was using ViteJS. So I need to add base in vite.config.js and package.json.

/* File: vite.config.js */
export default defineConfig({
  //...
  base: "/github-repo-name/",
});
/* File: packages.json */
{
 /*...*/
"scripts": {
 /* ... */
 "build": "vite build --base=/github-repo-name/",
 /* ... */
}

Hope this help

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.