Deploying React apps to GitHub pages

launching a React app/website onto a github.io subdomain

notes2023-09-06 23:10

Assuming that we have pushed up our React app to our remote Git repo, we will perform the following:

  • Install the gh-pages utility
  • Edit package.json for deployment
  • Deploy our app to GitHub page
  • Set up the remote repository for GitHub pages
  • Set ourselves up for re-deployment

Installing the gh-pages utility

Let us set up this package as a "dev dependency":

1$ npm install gh-pages --save-dev

Editing package.json for deployment

Add this JSON property to the package.json file, replacing yourname and yourrepo with the obvious:

"homepage" : "https://yourname.github.io/yourrepo"

Then, within the scripts property:

1"scripts" : {
2  "predeploy" : "npm run build", 
3  "deploy" : "gh-pages -d build", 
4  ...
5}

Overall, the package.json file should look something like:

1{
2"homepage": "https://yourname.github.io/yourrepo",
3"name": "reactetc",
4"description": "some react stuff",
5"version": "1.0.0",
6"main": "src/index.js",
7"dependencies": {
8   "react": "^17.0.0",
9   "react-dom": "^17.0.0",
10   "react-scripts": "^4.0.1",
11},
12"scripts": {
13   "predeploy" : "npm run build",
14   "deploy" : "gh-pages -d build",
15   "start": "react-scripts start",
16   "build": "react-scripts build"
17},
18"browserslist": [
19   "defaults"
20],
21"author": "yourname",
22"license": "MIT"
23}

Deploying the app

In Terminal, we can run the one-liner command:

$ npm run deploy

Setting up the remote repository for GitHub pages

On GitHub, assuming you have an account and everything:

  • Create a new remote repository (and note down its URL)
  • Go into the repository's Settings
    • Go to the section GitHub Pages
    • Under "Source":
      • Pick "Branch: gh-pages"
        • leave the folder at **** /(root)
      • Save

Wait a few seconds or a few minutes to see the page live on yourname.github.io/yourrepo

Re-deployment

For every time that we wish to re-deploy, we simply run these commands:

1$ git add -A
2$ git commit -m "pushing another version"
3$ git push origin master
4$ npm run deploy