Github Pages - 自动化构建并部署 Next.js 应用

具体步骤

1、新建 Github 仓库

仓库名称必须为 Github 用户名 + .github.io

2、创建 Next.js 应用

npx create-next-app@latest --typescript my-github-pages

3、本地运行

cd my-github-pages

yarn dev

运行成功后,使用浏览器打开 http://localhost:3000,即可正常访问:

4、修改代码

package.json 添加 export 命令 :

  "scripts": {
    "export": "next export",
  },

修改 pages/index.tsx,删除如下内容,避免构建静态文件失败:

...
import Image from 'next/image'
...
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
...

5、推送代码

rm -rf .git/
git init
git add .
git commit -m "init"
git branch -M main
git remote add origin git@github.com:AnoyiX/AnoyiX.github.io.git
git push -u origin main

6、添加 Github Actions

本地新建文件 .github/workflows/gh-pages.yml,并推送到仓库。

name: GitHub Pages

on:
  push:
    branches:
      - main
  pull_request:

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

      - name: Setup Node
        uses: actions/setup-node@v3
        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

推送成功后,Github Actions 会自动构建,并将生成的静态文件导出到分支 gh-pages,接下来只需设置 Pages 对应的分支即可:

切换分支后,稍微等待几十秒,即可通过域名 https://anoyix.github.io/ 正常访问我们的 NextJS 应用了。

后续只需将代码推送到 main 分支,应用就会自动构建、自动部署。

参考资料

推荐阅读更多精彩内容