LoginSignup
40
20

More than 1 year has passed since last update.

Gatsby のサイトを GitHub Actions で GitHub Pages にデプロイ

Last updated at Posted at 2019-09-15

Gatsby.js で構築しているブログ・サイトの GitHub Pages へのデプロイを GitHub Actions を利用して自動化する話です。

Gatsby のプロジェクトを用意

この記事では gatsbyjs/gatsby-starter-blog: Gatsby starter for creating a blog を例として用います。

GitHub Actions の設定

最新の情報は Action のリポジトリにて確認してください。

Workflow の追加

以下のワークフローを作って main ブランチへ Push すると自動的にサイトのビルドとデプロイが始まります。

.github/workflows/gh-pages.yml
name: GitHub Pages

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  deploy:
    runs-on: ubuntu-20.04
    concurrency:
      group: ${{ github.workflow }}-${{ github.ref }}
    steps:
      - uses: actions/checkout@v2

      - name: Setup Node
        uses: actions/setup-node@v2
        with:
          node-version: '14'

      - name: Cache dependencies
        uses: actions/cache@v2
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      - run: npm ci
      - run: npm run format
      - run: npm run test
      - run: npm run build

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        if: ${{ github.ref == 'refs/heads/main' }}
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./public

Project pages

User and Organization リポジトリ (username/username.github.io) の場合は GitHub Actions の workflow を追加するだけで十分です。一方で Project pages (username/project_name 形式のリポジトリ) の場合はいくつかの修正が必要です。

サイトは https://username.github.io/project_name/ 形式の URL で公開されます。

gatsby-config.js
module.exports = {
  pathPrefix: `/project_name`
}
package.json
"scripts": {
    "build": "gatsby build --prefix-paths"
}
40
20
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
40
20