Deploying React apps to GitHub pages

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

notes2024-08-04 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