How to Deploy CRA to GitHub Pages Using React Router

 ̄綄美尐妖づ 提交于 2019-12-24 21:37:22

问题


I have been majorly trapped by this curve ball.

I have a site built w/ create react app which I'd like to deploy to GitHub Pages, however, I've hit a blocker with React Router.

I understand GitHub pages work flawlessly w/ static content, but:

1- what is the correct solution to deploy to GitHub pages with SPA using react router ?

I tried all sort of configuration and none worked.

my routes are configured as:

Index.js

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from "react-router-dom";
import App from './App';
render(<Router basename={process.env.PUBLIC_URL}><App /></Router>, 
 document.getElementById('root'));

Routes.js

import { Route, Switch, Redirect, HashRouter } from 'react-router-dom';
...

const Routes = () => (
    <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/contact' exact component={Contact} />
        <Route path='/about/faculty' exact component={Faculty} />
        <Route path='/about/what-we-do' exact component={Mission} />
        <Redirect from='/about/' to='/about/faculty' />
        <Route component={NotFound} />
    </Switch>
)
export default Routes;

I tried wrapping my <Switch/> with <HashRouter/> but that made the routes no longer work.

My Package.json

{
  "name": "my-site",
  "version": "0.1.0",
  "private": true,
  "homepage": "https://username.github.io/project_name",
  "dependencies": {
    ...

    "react-router": "4.2.0",
    "react-router-bootstrap": "0.24.4",
    "react-router-dom": "4.2.2",
    "react-scripts": "1.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "devDependencies": {
    "gh-pages": "^1.1.0"
  }
}

After issuing a yarn build and yarn run deploy the site gets published to this page which holds no content at all, and naturally any route I try hitting gives me a 404.

2- Regarding the package.json what is the correct config for the homepage?:

"homepage": "https://username.github.io/project_name" or "homepage": "https://username.github.io"

As an end result, I'd like the site to be served under the https://username.github.io URL, so I'm confused about what is the correct configuration.

3 - I read docs stating that I should deploy under the gh pages branch which is actually not showing on my GitHub. I only get the option to publish to master.

来源:https://stackoverflow.com/questions/49045867/how-to-deploy-cra-to-github-pages-using-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!