How to Setup GitHub Pages with React
Recently, I want to setup a website using GitHub pages and use React as the Frontend framework. There are lots of resources in GitHub and Google around this combination. However, there are few points that need to be aware of when I actually try to create the GitHub page.
Prerequisite
- Having NodeJS installed. The main component is actually the “npm”. The version I am using is 14.16.1
- Having git installed
- Having a GitHub account
Create a GitHub repo for your page
You may refer to https://pages.github.com/ for the detailed steps.
Setup the React on Local Machine and Push to GitHub
Run the following to clone the repo from your remote GitHub repo and setup React.
# cd to the place/directory you want to save the code first
cd c:\Repo# install create-react-app globally
npm install -g create-react-app# create a brand new react project, you need to use npx for creating the project
npx create-react-app hopuichung.github.io# go into the created folder
cd hopuichung.github.io# install gh-pages package
npm install gh-pages --save-dev
Now we need to modify the package.json
for build and deployment.
- add homepage for your GitHub page URL. In my case, it is
https://hopuichung.github.io/
- add
"predeploy": "npm run build"
and"deploy": "gh-pages -d build"
to the scripts section
Your package.json
should look similar to this:
You may push it to master branch.
git add .
git commit -m "Create react app"
git push origin master
Build and Deploy the app
Run the following command to deploy your app to gh-pages
branch in GitHub.
npm run deploy
If you are facing the branch gh-pages already exists error, try to delete the
node_modules/.cache/gh-pages
folder and check your GitHub credential is correctly set… I faced this problem when I have a old GitHub account credential saved in my computer.
When everything is working, you may see the new gh-pages
branch in GitHub and your local repo.
Next, you may update the GitHub to point to the new gh-pages
branch for your GitHub pages.
Go to Settings/Pages, you may find the related setting and change it to gh-pages
.
Finally…
You may check your result at https://{your username}.github.io/
.
That’s the end of the initial setting. Next, you may start building your own React page via GitHub pages!