将react部署到github pages

1,346 阅读1分钟

部署静态网页

  1. 前往 github 官网,点击 New repository 创建新项目. 填入项目基本信息, 点击 Create Repository 确认.

  2. 代码clone到本地,新建一个html,上面写上 Hello Github! 代码推送到github

  3. 点击 settings -> Github Pages 需要选择一个主题(不知道什么原因,我最初没有选择,项目部署完成之后打开一直报404)

    settings -> Github Pages ->Source

    1596182563185

  4. 过一会之后,在Github Pages 下面可以看到一个地址,打开就能访问到自己的静态网页了

部署react项目

  1. 首先保证自己的react项目可以正常运行

  2. 将本地的项目关联到github

  3. cnpm i gh-pages --save-dev

  4. 修改本地项目的 package.json -> scripts 添加predeploy ,deploy

    "homepage": "https://{你的github名字}.github.io/{你的仓库名字}/",
    "scripts": {
        "start": "react-app-rewired start",
        "build": "react-app-rewired build",
        "test": "react-app-rewired test",
        "predeploy":"npm run build",
        "deploy": "gh-pages -d build"
      }
    
  5. 本地新建 git checkout -b gh-pages 分支

  6. 运行 npm run deploy

  7. 打开github上的项目 找到 settings -> Github Pages -> Source -> 保证选中的是 gh-pages

  8. settings -> Github Pages -> Source -> Theme Chooser 保证选中一个主题(我的没有选中,会报404,目前还不知道是什么原因)