【问题标题】:Deploying react app to github pages is publishing a blank page将 React 应用程序部署到 github 页面正在发布一个空白页面
【发布时间】:2021-10-13 16:05:05
【问题描述】:

我在本地机器上创建了一个个人网站,但我现在无法部署以将其发布到 github 页面。

网站仓库:https://github.com/vkodangattil/website

当我访问https://vkodangattil.github.io/website/ 时,我得到的只是一个空白页面,尽管我知道这个应用程序在 localhost 上运行良好。不知道该怎么做,我相信我在 package.json 文件中添加了正确的行,但我可能是错的。任何帮助将不胜感激

【问题讨论】:

    标签: reactjs github


    【解决方案1】:

    首先,您的所有路由都有相同的路径,因此您的路由只会选择第一个匹配的路径。

    function App() {
      return (
        <>
          <Router>
            <Navbar />
              <Route path='/' exact component=
              {Home} />
              <Route path='/' exact component=
              {AboutMe} />
              <Route path='/' exact component=
              {Resume} />
              <Route path='/' exact component=
              {Contact} />
          </Router>
        </>
      );
    }
    

    这是因为 GitHub 页面选择主页 URL 作为您的根路径,但是当它使用 /website 路径加载时。即使加载了 HTML,它也无法在空白页面中找到任何匹配的 URL 结果。

    要调整该 baseUrl,您需要将 basename 添加到 BrowserRouter。

    您的最终更改应该是:

    import './App.css';
    import Navbar from './components/Navbar';
    import { BrowserRouter, Switch, Route } from 'react-router-dom';
    import Home from './components/pages/Home';
    import Resume from './components/pages/Resume';
    import AboutMe from './components/pages/AboutMe';
    import Contact from './components/pages/Contact';
    
    function App() {
      return (
        <>
          <BrowserRouter basename="/website">
            <Navbar />
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/about-me" component={AboutMe} />
              <Route path="/resume" component={Resume} />
              <Route path="/contact" component={Contact} />
            </Switch>
          </BrowserRouter>
        </>
      );
    }
    
    export default App;
    

    【讨论】:

    • 我更改了主页并重新部署,但我仍然得到相同的空白页面
    • 嘿,我更新了我的回复。为什么要使用HashRouter?这将导致您的 URL 末尾有一个额外的 #,这与您的部署 gh 页面不匹配。告诉我它是否仍然不适合你。
    • 您好,感谢您的回复。我更改为 HashRouter,因为我看到几个答案说 BrowserRouter 不适用于 GitHub 页面。我做了你建议的更改,但是我仍然得到一个空白页
    • 嘿,对不起,我更新了答案。关键是将 package.json 中的主页保留为:https://vkodangattil.github.io/website,然后在您的BrowserRouter 中添加一个额外的basename="/website",因此 gh 页面会将您的根路径与定义的 homepage 中的 baseUrl 同步。
    • 还有一点需要注意的是,如果您尝试直接访问https://github.com/vkodangattil/website/about-me 它将不起作用,因为 gh-page 在该文件 URL 中找不到 index.html 文件。但是,您仍然可以从 Link 组件的客户端访问这些页面。
    猜你喜欢
    • 2021-01-12
    • 2021-12-22
    • 1970-01-01
    • 2017-11-03
    • 2021-02-14
    • 2021-08-16
    • 1970-01-01
    • 2021-11-28
    • 2020-02-03
    相关资源
    最近更新 更多