简体   繁体   English

将React App部署到GitHub页面中的子文件夹时的相对路径问题

[英]Problem with relative path when deploying react app to a subfolder in GitHub pages

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" /> 在我的Home组件和About组件中,我有两个图像,其中src设置为: <img src="/img/charlie1.jpg" alt="charlie home pic" /><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 但是,当我建立它和移动文件督促图像将不能工作,寻找图像在此路径: https://xyz.github.io/img/charlie2.jpg而不是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" /> 如果我将图像src更改为: <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… 然后它可以在github页面上工作,但是当我在本地计算机上时,图像将不会显示…

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. 将图像导入JavaScript并尽可能使用导入的变量是个好主意,而URL只能自己工作。

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 . 如果页面的根不是/并且在public目录中有资产,则很可能必须在代码中一些额外的逻辑

package.json 的package.json

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

App.js App.js

<img src={`${process.env.PUBLIC_URL}/img/charlie1.jpg`} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM