简体   繁体   English

GitHub Pages 上的 React 应用程序 - URL 缺少存储库名称

[英]React app on GitHub Pages - URL missing repository name

I am keeping images in a folder public/assets/img .我将图像保存在public/assets/img文件夹中。 Then I use it in a component like that:然后我在这样的组件中使用它:

const imageUrl = "/assets/img/image.png"

Locally everything works fine, but on GitHub Pages in an image URL somehow name of my repo is missing, so instead of在本地一切正常,但在图像 URL 中的 GitHub 页面上不知何故我的存储库名称丢失,因此而不是

http://name.github.io/my-repo/assets/img/image.png I get http://name.github.io/assets/img/image.png http://name.github.io/my-repo/assets/img/image.png我得到http://name.github.io/assets/img/image.png

I was following an instruction on how to create a GitHub Pages build and added in package.json the URL of my project, namely "homepage": "https://name.github.io/my-repo"我正在遵循有关如何创建 GitHub 页面构建的说明,并在 package.json 中添加了我的项目的 URL,即"homepage": "https://name.github.io/my-repo"

-- edit -- - 编辑 -

Also, I've just now realized, that although the routing seems to work fine, it also misses my repository name in the URL, so instead of另外,我刚刚意识到,虽然路由似乎工作正常,但它在 URL 中也缺少我的存储库名称,因此而不是

http://name.github.io/my-repo/subpage there is http://name.github.io/my-repo/subpage

http://name.github.io/subpage

What am I missing here?我在这里缺少什么?

OK, so I somehow have solved my problems, however, I am not quite satisfied with the solutions:好的,所以我以某种方式解决了我的问题,但是,我对解决方案不太满意:

Fixing the URL problem (missing repo name in the URL)修复 URL 问题URL 中缺少 repo 名称)

I've added a basename property to my router <BrowserRouter basename="/repo-name">我在路由器<BrowserRouter basename="/repo-name">添加了basename属性

Downsides: Firstly, it doesn't look good hardcoded.缺点:首先,它看起来不太好硬编码。 Secondly, npm start opens localhost:3000 which is empty now.其次, npm start打开localhost:3000现在是空的。 I have to add my repo name to open the app locally, so localhost:3000/repo-name - not too neat.我必须添加我的 repo 名称才能在本地打开应用程序,所以localhost:3000/repo-name - 不太整洁。

Fixing images problem (also missing repo name in the URL and thus not displaying images)修复图像问题(URL 中也缺少 repo 名称,因此不显示图像)

I've added a process.env.PUBLIC_URL variable to the image URL: const imageUrl = ${process.env.PUBLIC_URL}/assets/img/image.png .我已将process.env.PUBLIC_URL变量添加到图像 URL: const imageUrl = ${process.env.PUBLIC_URL}/assets/img/image.png In local environment it's empty, deployed it takes homepage value from package.json , which is https://name.github.io/repo-name在本地环境中它是空的,部署它从package.json获取homepage值,即https://name.github.io/repo-name

Downside: one has to add process.env.PUBLIC_URL before every image displayed in a component.缺点:必须在组件中显示的每个图像之前添加process.env.PUBLIC_URL

I would be grateful for any better solution!如果有更好的解决方案,我将不胜感激!

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

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