文章12
标签10
分类3

使用github部署React项目

一般来说部署React项目需要购买服务器,但是对于一些demo类型的项目,购买服务器尤其不划算,我们可以使用Github提供的gitpage对其部署。

那么如何将我们的React项目部署到github呢?

1.创建Github仓库:

2.将React项目上传至Github:

git init
git remote add origin https://github.com/qq995473428/jianshu.git
git add . //将所有文件上传
git commit -m 'jianshu'
git branch //查询当前分支
git push origin master:master

3.安装gh-pages:

npm install gh-pages --save-dev

4.修改本地React项目的package,json文件:

{
  "name": "jianshu",
  "version": "0.1.0",
  "homepage": "https://qq995473428.github.io/jianshu", //步骤1
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "immutable": "^4.0.0-rc.12",
    "react": "^16.10.2",
    "react-dom": "^16.10.2",
    "react-loadable": "^5.5.0",
    "react-redux": "^7.1.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0",
    "react-transition-group": "^4.3.0",
    "redux": "^4.0.4",
    "redux-immutable": "^4.0.0",
    "redux-thunk": "^2.3.0",
    "styled-components": "^4.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "deploy": "gh-pages -d build",//步骤2
    "predeploy": "npm run build" //步骤3
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^2.1.1"
  }
}

步骤1

加入homepage 地址为github仓库地址,但需要改动一下,比如我的仓库地址是https://github.com/qq995473428/jianshu 那我就要改为https://qq995473428.github.io/jianshu

步骤2 && 步骤3

配置发布选项

"predeploy": "npm run build", 
 "deploy": "gh-pages -d build"

5.修改接口地址:

由于我使用的是在Public目录自己创建json文件当作接口数据,所以我所有的接口请求地址前面要加一个jianshu,按照github给的仓库地址链接的路径更改,Router有路径地址的话,也按仓库的地址进行修改:

 axios.get('/jianshu/api/login.json?account=' + account + '&password= ' + password).then((res) => {
const result = res.data.data;
if (result) {
dispatch(changeLogin());
}else {
alert('登录失败');
}
})

6.部署项目到Github上:

npm run deploy

检查github分支会多出一个gh-pages分支,进入里面的setting就可以看到演示地址

演示地址: https://qq995473428.github.io/jianshu/

本文作者:Bunrun
本文链接:https://www.bugrun.cn/posts/1715.html
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可