Github page部署react 应用

44 阅读2分钟

通过在github 上创建 public project来部署静态网站

demo代码 react web
demo线上访问地址

部署简单web网站

  1. 创建github public 仓库:github-page-demo并且创建分支simple-html
  2. 创建index.html
    $ echo "Hello World" > index.html
  3. push index.html
    $ git add --all
    $ git commit -m "Initial commit"
    $ git push -u origin simple-html
  4. Deploy 配置simple-html分支页面:访问github仓库 按照如下步骤
    image.png Branch 选项中选择 simple-html分支 文件选择/root会去自动识别根目录下的html文件

部署react web网站

  1. 还是上述仓库创建 react-page-demo 分支,通过create-react-app快速创建react项目
    npx create-react-app ./
    提交生成的代码

  2. 自定义项目配置:执行npm run eject

  3. 修改github page 监听的分支和发布的source路径,从/(root)改为根目录下/docs

image.png

  1. 本地创建docs文件,当build完成后的文件复制到docs中,这里通过 copyfiles 对文件进行拷贝

安装 copyfilesnpm i copyfiles --save-dev
配置 script

// package.json
"scripts": {
    "build": "node scripts/build.js && npm run copy",
    "copy": "rm -rf docs/* && copyfiles -u 1 'build/**/*' docs/",
  }
  1. package.json homepage定义为相对路径
// package.json
  "homepage": "./",

运行npm run build 并提交代码到远程仓库,直接访问github page url

react-router

  1. 安装 react-router-dom 包npm i --save react-router-dom@5.3.3 --force
  2. 创建两个页面home.js,detal.js 互相指向跳转
// src/pages/home.js
import { Link } from "react-router-dom";

function Home() {
  return (
    <div
      className="home"
      style={{
        height: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <h2>Home page</h2>
      <Link to="/detail">
        <h3>go to detail</h3>
      </Link>
    </div>
  );
}

export default Home;

// src/pages/detail.js
import { Link } from "react-router-dom";

function Detail() {
  return (
    <div
      className="home"
      style={{
        height: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <h2>Detail page</h2>
      <Link to="/">
        <h3>go to home</h3>
      </Link>
    </div>
  );
}

export default Detail;

  1. App.js router 注册
// App.js
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";
import Home from "./pages/home";
import Detail from "./pages/detail";
import "./App.css";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/detail" component={Detail} />
        <Route path="/" component={Home} />
      </Switch>
    </Router>
  );
}

export default App;

  1. 访问本地网络,测试路由是否可以正常跳转,之后进行打包推送代码到远程仓库,但当点击detail页面 link to \ 跳转,url变为https://luopeihai.github.io/ 不是预期url:https://luopeihai.github.io/github-page-demo/

添加 basename解决这个问题

//App.js
 <Router basename={"/github-page-demo"}>
      <Switch>
        <Route path="/detail" component={Detail} />
        <Route path="/" component={Home} />
      </Switch>
    </Router>