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?

GitHub Pagesの404対策(Vite)

Posted at

GtiHub Pagesでデプロイした場合,初期状態では/以外のページにアクセスすると404 not foundになる問題の対策(無理やり解決)

vite.config.ts

baseをリポジトリ名にしておく

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
    plugins: [react(), { enforce: "pre", ...mdx(options) }],
    base: "/RepositoryName/", //リポジトリ名を指定
});

deploy.yml

deploy.ymlを以下のようにする.

今回の404対策は404.htmlを作成の行

name: Build and Deploy to gh-pages

on:
    push:
        branches: [main]

permissions:
    contents: write
    pages: write # 必須: Pagesに書き込み権限を与える
    id-token: write # GitHub OIDCトークンにアクセスするために必要

jobs:
    build:
        runs-on: ubuntu-latest
        steps:
            # コードのチェックアウト
            - uses: actions/checkout@v4

            # Node.jsのセットアップ
            - uses: actions/setup-node@v3
              with:
                  node-version: "20"

            # Node.jsモジュールのキャッシュ
            - name: Cache Node.js modules
              uses: actions/cache@v3
              with:
                  path: ~/.npm
                  key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
                  restore-keys: |
                      ${{ runner.os }}-node-

            # Node.js依存関係のインストール
            - run: npm ci

            # ビルドの実行 (distフォルダにビルド)
            - name: Build
              run: npm run build

            # 404.htmlを生成
            - name: Generate 404.html
              run: cp dist/index.html dist/404.html

            # GitHub Pagesの設定
            - name: Setup Pages
              uses: actions/configure-pages@v5

            # distフォルダをアーティファクトとしてアップロード
            - name: Upload artifact
              uses: actions/upload-pages-artifact@v3
              with:
                  # distフォルダのみアップロード
                  path: "dist"

            # GitHub Pagesにデプロイ
            - name: Deploy to GitHub Pages
              id: deployment
              uses: actions/deploy-pages@v4

まとめ

これでmainブランチにマージしたタイミングで自動的にビルドからデプロイまでしてくれるかつ/以外のパスにアクセスしても404を吐かなくなった.

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?