なんじゃくにっき

プログラミングの話題中心。

GatsbyのプロジェクトビルドからGitHub PagesにGithub Actionsでデプロイするまで

Gatsbyの初期設定

静的サイトジェネレーターのGatsbyを動かします。Github Pagesにデプロイして動かすまで。

gatsuby-cliのインストール

npm install -g gatsby-cli

一旦shellを読み込み直します

$SHELL -l

プロジェクト作成

gatsby new your_project_name

デザインのテーマ(?)を指定したいときはgatsbyコマンドの3つ目の引数にurlを指定します。指定しない場合はデフォルトのものが使われます。

gatsby new your_project_name https://github.com/gatsbyjs/gatsby-starter-hello-world

テーマ(?)はここで探せます。

Starters Library | Gatsby

git

githubリポジトリ作成して

ローカルでgit initしてから

git remote set-url origin https://github.com/nanjakkun/hogehoge.git

テストの導入(jest)

npm install --save-dev jest

package.json

"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"

となっているところを

"test": "jest"

と書き換えます。

tests/dummy.test.js というファイルを作って中身を

test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});

として

npm run test

が通ることを確認します。

pathが機能するようにする

Github Pagesではuser_name.github.io/project_nameのようにサブディレクトリの位置に公開されるので、

Github Pages内のパスを変換しないとリンクが切れてしまう。

そこで、gatsby-config.jsを

module.exports = {
  pathPrefix: `/project_name`
}

のようにし、

package.jsonのbuild部分も

    "build": "gatsby build --prefix-paths",

に書き換える。

Github Actions やり方1

GithubリポジトリのページからSettings -> Pages

gatsbyの設定ファイルがリポジトリにあると、gatsbygithub actionsを追加するようにsuggestしてくるのでそこからPRを作る。

一旦mainにmergeするか、PRをcheck outしてきて編集する

  • 自動的に作成されるyamlではPull Requestに対して動かないので動くようにする
  • test実行を入れる
# Sample workflow for building and deploying a Gatsby site to GitHub Pages
#
# To get started with Gatsby see: https://www.gatsbyjs.com/docs/quick-start/
#
name: Deploy Gatsby site to Pages

on:
  # Runs on pushes targeting the default branch
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: "pages"
  cancel-in-progress: false

# Default to bash
defaults:
  run:
    shell: bash

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Detect package manager
        id: detect-package-manager
        run: |
          if [ -f "${{ github.workspace }}/yarn.lock" ]; then
            echo "manager=yarn" >> $GITHUB_OUTPUT
            echo "command=install" >> $GITHUB_OUTPUT
            exit 0
          elif [ -f "${{ github.workspace }}/package.json" ]; then
            echo "manager=npm" >> $GITHUB_OUTPUT
            echo "command=ci" >> $GITHUB_OUTPUT
            exit 0
          else
            echo "Unable to determine package manager"
            exit 1
          fi
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: ${{ steps.detect-package-manager.outputs.manager }}
      - name: Setup Pages
        id: pages
        uses: actions/configure-pages@v5
        with:
          # Automatically inject pathPrefix in your Gatsby configuration file.
          #
          # You may remove this line if you want to manage the configuration yourself.
          static_site_generator: gatsby
      - name: Restore cache
        uses: actions/cache@v4
        with:
          path: |
            public
            .cache
          key: ${{ runner.os }}-gatsby-build-${{ hashFiles('public') }}
          restore-keys: |
            ${{ runner.os }}-gatsby-build-
      - name: Install dependencies
        run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }}
      - name: Run test
        run: npm run test
      - name: Build with Gatsby
        env:
          PREFIX_PATHS: 'true'
        run: ${{ steps.detect-package-manager.outputs.manager }} run build
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./public

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    if: ${{ github.ref == 'refs/heads/main' }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

このActionの中でpathnameの書き換えもやってくれている模様。

Github Actions やり方2

※少し古いやり方。このやり方でも動きますが、やり方1のほうが楽だと思います。

Github Actionsでデプロイするようにします。

動きとしては以下のようにします。

  • node_modulesはキャッシュさせる
  • testが通ってたらdeployさせる
  • Pull requestに対してはtestは動かすがdeployは動かさない

※Actionのバージョンは古くなっていることがあるので最新のバージョンを確認して下さい

.github/workflows/test_and_deploy.yml

name: Test and Deploy

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest
    concurrency:
      group: ${{ github.workflow }}-${{ github.ref }}
    steps:
      - uses: actions/checkout@v4
      - name: Set uo Node
        uses: actions/setup-node@v4
        with:
          node-version: 20
      - uses: actions/cache@v4
        id: node_modules_cache_id
        env:
          cache-name: cache-node-modules
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
          restore-keys: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
      - if: ${{ steps.node_modules_cache_id.outputs.cache-hit != 'true' }}
        run: npm install
      - run: npm run test

  deploy:
    needs: test
    if: ${{ github.ref == 'refs/heads/main' }}
    runs-on: ubuntu-latest
    concurrency:
      group: ${{ github.workflow }}-${{ github.ref }}
    steps:
      - uses: actions/checkout@v4
      - name: Set uo Node
        uses: actions/setup-node@v4
        with:
          node-version: 20
      - uses: actions/cache@v4
        id: node_modules_cache_id
        env:
          cache-name: cache-node-modules
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
          restore-keys: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
      - if: ${{ steps.node_modules_cache_id.outputs.cache-hit != 'true' }}
        run: npm install
      - run: npm run build
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./public

※gh-actionでPermission系のエラーが出たら Github のSettings -> Actionsから権限をReadからRead and Writeに変える