iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

How to Publish a React App on GitHub Pages

に公開

Introduction

I created a simple memo app while studying React.
I wanted to publish the app I created for free, so I tried using GitHub Pages.
In this article, I will introduce the steps to deploy a React app on GitHub Pages.

What is GitHub Pages?

GitHub Pages is a static site hosting service provided by GitHub.
By using GitHub Pages, you can publish repositories that are on GitHub.

Created App

Simple Memo
Repository

Steps to Deploy a React App on GitHub Pages

1. Edit the package.json of the app you want to publish

Edit the package.json of the app you want to publish as follows.

package.json
{
  ...
  "homepage": "https://<GitHub-Account-Name>.github.io/<GitHub-Repository-Name>/",
  ...
  "scripts": {
    ...
    "rm": "rm -rf docs",
    "mv": "mv build docs",
    "git": "git add . && git commit && git push origin master",
    "deploy": "npm run rm && npm run build && npm run mv && npm run git"
  },
}
  • "..." are omitted.

Set the deployment URL in the homepage field of package.json.

Also, the scripts added to the scripts section of package.json are as follows:

rm: Script to delete the docs directory
mv: Script to move the build directory to the docs directory
git: Script to push the docs directory to GitHub
deploy: Script to execute rm, build, mv, and git in sequence

Only the deploy script is used.
By running deploy, the following actions will be performed:

  • Delete the docs directory (to remove old files)
  • Build the app
  • Move the build directory to the docs directory
  • Push the docs directory to GitHub

2. Create a branch for deployment

Create a branch for deployment.
The name of the branch for deployment will be gh-pages.

3. Deploy on the deployment branch

Run deploy on the deployment branch.

npm run deploy

4. Configure GitHub Pages settings

To use GitHub Pages, you need to configure the settings.
You can access the GitHub Pages settings from the "Settings" tab of your repository on GitHub.

  1. Change "Source" to "Deploy from a branch"
  2. Change "Branch" to "gh-pages"
  3. Change the publishing folder to "/docs"
  4. Click the "Save" button

5. Confirm the deployment

Check if the site is published.
If it is not live yet, it may take a short while, so please wait and check again after a bit.

Summary

I introduced the steps to publish a React app on GitHub Pages.
By using GitHub Pages, you can publish your apps for free.

Discussion