1
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?

GithubPagesにSPAで公開する

Last updated at Posted at 2025-02-10

GoogleAnalyticsの検証をしたく、ホスティングする必要が生じたので簡単に無料でできるGithuPagesを試してみます。
React×TypeScriptの環境で行っています。
Viteを利用しているので、適宜ビルドの出力先のディレクトリ名を読み替えてください。

手順

コマンド、package.jsonの修正内容はまとめて手順の後ろに記載しています。

  1. Repositoryの作成(Public)
  2. Reactプロジェクトにgh-pagesをインストール
  3. package.jsonにhomepageを追記
  4. package.jsonのscriptに追記
  5. vite.config..tsに追記
  6. mainブランチにpush
  7. デプロイ(ここで自動でブランチ作成される)
  8. GitHubのリポジトリの設定(Pages)を変更
npm install gh-pages --save-dev
package.json
"homepage": "https://<github_userName>.github.io/<repository_name>"
package.json
"script": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d dist" // {dist | build} ビルド出力先に読み替え必要
}
vite.config.ts
export default defineConfig({
  plugins: [react()],
  base: '/<repository_name>/'
})
npm run deploy

image.png

追加設定

React Routerなどのルーティングライブラリを使用している場合は、追加の設定が必要になります。
basenameをGithubPagesと一致させてあげます。

GithubActionを用いた自動デプロイ

プロジェクトルートに.github/workflows/deploy.ymlを作成

.github/workflows/deploy.yml
name: vite-app-deploy
on:
  push:
    branches:
      - main
jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 18
          cache: npm
      - name: Install dependencies
        run : npm install
      - name: Build project
        run : npm run build
      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@v4
        with: 
          branch: gh-pages
          folder: dist
          clean : true

Repositoryの
設定 > Actions > General > Workflow permissions
Read and write permissionsにh

1
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
1
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?