0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Viteによって作成したReactアプリをGithub Pagesを使ってデプロイ!

Posted at

はじめに

前回、以下の記事でデプロイした際に画面が真っ白になったことを紹介しました。

今回の記事では、デプロイの流れを忘備録として記録しておこうかと思います。

※こちらの記事は

https://ユーザ名.github.io/リポジトリ名/

のようなURLにデプロイすることを想定しています。

デプロイ

利用するツール

Github Actions :

デプロイをする際に利用します。

また、指定したブランチにpushを行った際の行動などをworkflowsとして決めることで、自動でデプロイを行うことを可能にします。

デプロイの流れ

大きな流れとしては、以下のVite公式を参考にしています。


まず、vite.config.ts に以下のコードを追加することで、baseを指定します。

base: import.meta.env.DEV 
    ? "/" 
    : "/リポジトリ名/",

これにより、開発環境か否かでURLのbase部分を変更することができます。


次に、Githubのデプロイを行いたいアプリのrepositoryを開き、Settings をクリックします。

スクリーンショット 2023-11-26 11.50.20.png

そして、Settingsで Pages をクリック

SourceGithub Actionsを選択

最後に、Static HTML を選択します。

スクリーンショット 2023-11-26 11.55.24.png


すると .Github/workflows/static.yml を編集するページに飛ばされるので、以下のコードをコピペします。

# 静的コンテンツを GitHub Pages にデプロイするためのシンプルなワークフロー
name: Deploy static content to Pages

on:
  # デフォルトブランチを対象としたプッシュ時にで実行されます
  push:
    branches: ['main']

  # Actions タブから手動でワークフローを実行できるようにします
  workflow_dispatch:

# GITHUB_TOKEN のパーミッションを設定し、GitHub Pages へのデプロイを許可します
permissions:
  contents: read
  pages: write
  id-token: write

# 1 つの同時デプロイメントを可能にする
concurrency:
  group: 'pages'
  cancel-in-progress: true

jobs:
  # デプロイするだけなので、単一のデプロイジョブ
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Set up Node
        uses: actions/setup-node@v3
        with:
          node-version: 18
          cache: 'npm'
      - name: Install dependencies
        run: npm install
      - name: Build
        run: npm run build
      - name: Setup Pages
        uses: actions/configure-pages@v3
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v2
        with:
          # dist リポジトリのアップロード
          path: './dist'
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v2

上記のコードは、mainブランチにpushが行われた際に、自動的にデプロイすることを可能にしています。

最後に、commit changesを行なってstatic.ymlを更新しましょう。

React Router の利用者向け

React Router を利用している方は main.tsxBrowserRouter を以下のように編集します。

<BrowserRouter basename={import.meta.env.DEV ? "/" : "/リポジトリ名/"}>
    <App />
  </BrowserRouter>

これにより、React Routerが誤ったURLを開くことを防ぎます。

終わりに

以上によって、デプロイ先のURLを開くとアプリを利用することが可能になっているはずです!

お読み頂きありがとうございます。
少しでもこの記事がお役に立てると光栄です!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?