Reputation: 3245
I have a react app with this project structure:
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…
Upvotes: 2
Views: 2340
Reputation: 195
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
Upvotes: 0
Reputation: 112787
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`} />
Upvotes: 1