为什么Github页面网址在加载时发生更改,导致公共资源路径不正确?

问题描述 投票:0回答:2

我有一个用create-react-app制作的React页面,我按照here的说明将它部署到github页面。它将打开,但是未加载公共目录上的资源。似乎正在发生的情况是,在页面加载期间,http:// {name} .github.io / {repo}被截断为http:// {name} .github.io,因此在页面尝试加载公共目录时,公共目录的相对路径不再正确。如果我尝试使用url http:// {name} .github.io重新加载页面,则会收到404错误。

我可以更改使其正常工作的路径,但这感觉就像是骇客。我想知道这里发生了什么,如果可能的话,我将如何解决。

reactjs redirect deployment github-pages
2个回答
0
投票

您需要在package.json中定义的主页

“主页”:“ http://gitname.github.io/react-gh-pages

https://github.com/gitname/react-gh-pages#procedure


0
投票

如果看不到您的代码,很难说。但是,react-router可能设置不正确。

您应该这样设置路由器:

import { BrowserRouter as Router } from ‘react-router-dom’;

const routerBaseName = process.env.PUBLIC_URL;

ReactDOM.render(<Router basename={routerBaseName}>< App /></Router>, document.getElementById(‘root’));

注意basename部分-构建捆绑包时,应将其设置为生产URL(在这种情况下为https://CBreakr.github.io/ATTCK_StarWars/

在本地进行开发时,应将其设置为您的本地主机URL。

您可以使用.env文件设置PUBLIC_URL的值(我相信使用create-react-app时,您必须将其更改为REACT_APP_PUBLIC_URL

© www.soinside.com 2019 - 2024. All rights reserved.