Hosting a React App on GitHub Pages
In this guide, I'll walk you through the steps to host your React app on GitHub Pages.
Step 1: Create a GitHub Repository
- Go to GitHub and create a new repository.
- Name the repository (e.g.,
my-react-app). - Optionally, initialize the repository with a
README.mdfile.
Step 2: Install gh-pages
Navigate to your React app's directory and install the gh-pages package:
npm install gh-pages --save-dev
Step 3: Update package.json
Open your package.json file and make the following changes:
Add a homepage Field
At the top of your package.json, add:
"homepage": "https://<your-username>.github.io<your-repository-name>"
Replace <your-username> with your GitHub username and <your-repository-name> with the name of your repository.
Add Deployment Scripts
Add the following scripts to the scripts section of package.json:
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
-
predeploy: Automatically runsnpm run buildbefore deploying. -
deploy: Deploys the contents of thebuilddirectory to thegh-pagesbranch.
Step 4: Build and Deploy
Run the following command to build and deploy your app:
npm run deploy
This command creates a production build of your app and pushes it to a gh-pages branch in your repository.
Step 5: Configure GitHub Pages
- Go to your repository on GitHub.
- Click on the "Settings" tab.
- Scroll down to the "GitHub Pages" section.
- Under "Branch," select
gh-pages.
Your React app should now be live on GitHub Pages at https://<your-username>.github.io/<your-repository-name>.
Top comments (0)