In this guide, I will be walking you through how to deploy a React application created with create-react-app to gh-pages.
This guide assumes some level of familiarity with Git and command line interfaces.
According to the documentation, gh-pages is a static site hosting service that takes HTML, CSS, and JavaScript files straight from a repository on GitHub, optionally runs the files through a build process, and publishes a website.
We will walk through three steps for deploying a React application.
Let's start by creating a new repo:
guide-react-gh-pages
Open up your terminal and type the following command:
1npx create-react-app guide-react-gh-pages
This will create a new folder named guide-react-gh-pages
(or whatever you named your app). Then follow the instructions on how to start and run the application.
Navigate to the folder that was just created.
1cd /path/to/guide-react-gh-pages
Link and push your newly created project to Github Repository.
1git init
2git add .
3git commit -m "first commit"
4git remote add origin [email protected]:username/guide-react-gh-pages.git
5git push -u origin master
Still in the terminal and in the folder for your app, follow these steps:
Install the gh-pages as a dev-dependency
1npm install gh-pages --save-dev
Open the app's packaage.json
file and
Add an homepage
field with its value to be the string http://{username}.github.io/{repo-name}
, where {username}
is your GitHub username, and {repo-name}
is the name of the GitHub repository you created in Step 1.
1"homepage": "https://myusername.github.io/guide-react-gh-pages",
If you skip the step, the app will not deploy correctly because create-react-app uses the homepage field to determine the root URL in the built HTML file.
Update the existing scripts
field with the following:
1"scripts": {
2 "predeploy": "npm run build",
3 "deploy": "gh-pages -d build",
4 "start": "react-scripts start",
5 "build": "react-scripts build",
6}
Deploy the app.
1npm run deploy
The predeploy
script will run automatically before deploy
is run.
Voila! The app is now accessible at the URL you specified in the homepage
field in the package.json
file.
This guide has provided a walkthrough on how you can publish your React application to gh-pages with a few easy steps using create-react-app and gh-pages npm package.
Here is a useful link if you'd like to learn more: