LoginSignup
32
21

More than 1 year has passed since last update.

React Next アプリを GitHub Actions で GitHub Pages にデプロイ

Last updated at Posted at 2019-09-14

React.js で作成したアプリケーション、とりわけ今回は Next.js で始めたプロジェクトを例に GitHub Actions を使って GitHub Pages へのデプロイを自動化する方法を紹介します。

Vue, Nuxt についての記事もあります。

Create Next App

上記を参考に Next のプロジェクトを作成してください。この記事作成時の Next バージョンは 9.0.5 です。

GitHub Actions の設定

peaceiris/actions-gh-pages: GitHub Actions for deploying to GitHub Pages with Static Site Generators を利用します。

GitHub Actions を用いた GitHub Pages へのデプロイ自動化方法についてより詳しく知りたい方は上記記事を参考にしてください。

以下のファイルを main ブランチに Push してください。自動で GitHub Actions による Next のビルドと GitHub Pages へのデプロイが始まります。

名称が username/username.github.io の repository であれば https://username.github.io/ 形式の URL で Web app が公開されます。

.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: Get yarn cache
        id: yarn-cache
        run: echo "::set-output name=dir::$(yarn cache dir)"

      - name: Cache dependencies
        uses: actions/cache@v2
        with:
          path: ${{ steps.yarn-cache.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - run: yarn install --frozen-lockfile
      - run: yarn build
      - run: yarn export

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

Project pages

User and Organization リポジトリ (username/username.github.io) の場合は GitHub Actions の workflow を追加するだけで十分です。一方で Project pages (username/project_name 形式のリポジトリ) の場合は next.config.js に対して以下のような修正が必要です。

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

next.config.js
module.exports = {
  // some configuration
  assetPrefix: process.env.NODE_ENV === "production" ? "/project_name" : ""
  // another configuration
};
package.json
"scripts": {
  "build": "env NODE_ENV='production' next build"
}

独自ドメイン

GitHub Pages へデプロイした React, Next アプリケーションを独自ドメインで公開する手順です。

User and Organization リポジトリで公開するために next.config.js を修正していた場合は取り消しておきます。

以下の記事でも独自ドメインの設定方法を解説しているので参考にしてください。

CNAME./out に加える step を export step の後に追加します。

- name: add CNAME
  run: cp ./path/to/CNAME ./out/

参考

32
21
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
32
21