iTranslated by AI

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

Deploying React (+Vite) to GitHub Pages

に公開

I deployed a React (+Vite) SPA using GitHub Actions' actions/deploy-pages@v1, so I'm documenting how to do it here.

GitHub Actions Configuration

It seems that people used to use peaceiris/actions-gh-pages in the past, but it has apparently become easier to do with the official actions/deploy-pages@v1 (this was my first time using it).

The final GitHub Action definition is as follows:

name: deploy

on:
  push:
    branches: ['main']
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: 'pages'
  cancel-in-progress: true

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Setup Node
        uses: actions/setup-node@v3
        with:
          node-version: 18
          # Set up to enable yarn caching (use npm if you are using npm)
          cache: yarn
      - name: yarn install
        run: yarn install
      - name: yarn build
        run: yarn build
        # GitHub Pages will be https://USERNAME.github.io/REPOSITORY_NAME/,
        # so we add an env variable to change the Vite base path.
        env:
          GITHUB_PAGES: true
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v1
        with:
          path: ./dist

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v1

Vite Configuration

As mentioned in the comments above, GitHub Pages will be https://USERNAME.github.io/REPOSITORY_NAME/, so if you publish React as is, it will result in a 404 error.

Therefore, we modify vite.config so that the BasePath changes when it is on GitHub.

vite.config.ts
export default defineConfig({
  /* ...omitted... */
  base: process.env.GITHUB_PAGES
    ? 'REPOSITORY_NAME' // Set your repository name
    : './'
});

React Router Configuration

Also, change the React side to load Vite's BASE_URL.

<BrowserRouter basename={import.meta.env.BASE_URL}>
  {children}
</Router>

That's it. It has become very convenient to host SPAs easily.

GitHubで編集を提案

Discussion