LoginSignup
3
4

More than 1 year has passed since last update.

5分くらいで作るReact+GitHub Pagesの自動デプロイ環境

Posted at

Reactで作ったページをGitHub Pagesに自動デプロイするメモ。
mac環境で作成しています。その他実行時のバージョンは以下。

  • node: 18.0
  • npm: 8.6.0
  • create-react-app: 5.0.1

React プロジェクトを作成する

npx create-react-app react-gh-pages

GitHub Actionのworkflowを作成する

作成したReactプロジェクトに移動し、ymlファイルを作成します。

cd react-gh-pages && mkdir -p .github/workflows/ && touch .github/workflows/deploy.yml

作成したymlファイルに下記の内容をコピペします。

name: Build and Deploy

on:
  push:
    branches: [master]

permissions: write-all

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [18.x]
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
          cache: "npm"

      - name: Build
        run: |
          npm ci
          npm run build

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./build

package.jsonにGitHub PagesのURLを追記する。

URLは、デフォルトだとhttps://<GitHubアカウント名>.github.io/<リポジトリ名>/になっているので今回はそれを追記しています。

  "homepage": "https://hono3bono3.github.io/react-gh-pages/"

コミットしてGitHubにpush

ソースコード側の作業は完了なのでここまでの内容をリポジトリに反映させます。
今回はゼロから作成したので、GitHub CLIで直接リポジトリを作成しています。

git add .
git commit -m "GitHub Pagesの設定追加"
gh repo create

GitHub Pagesに公開するブランチを設定する

push後、GitHubのリポジトリ上でActionsタブを開くと、先ほど作成したworkflowが実行されているので
完了するまで待ちます。
スクリーンショット 2022-05-03 16.18.34.png

完了後、Settingタブを開き、左のPagesをクリックする。SourceのNoneをクリックすると
gh-pagesブランチが作成されているので選択しSave.
スクリーンショット 2022-05-03 16.20.24.png

再度、Actionsタブを開くと、新しくworkflowが走っているので完了するまで待ちます。
スクリーンショット 2022-05-03 16.20.51.png

完了後、URLにアクセスすると反映されているのが確認できます。
スクリーンショット 2022-05-03 16.21.50.png

あとは masterに変更が入るたびに、build ~ deployまで自動で回るようになっています。

スクリーンショット 2022-05-03 16.36.08.png
スクリーンショット 2022-05-03 16.36.16.png

ソースコードは下記URLに公開しています。
https://github.com/hono3bono3/react-gh-pages

参考資料

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4