解决Next.js14在GitHub Pages部署的关键问题

👋这次在github page部署Next.js项目时,碰上了不少的问题,但是很多问题在查阅过程中发现缺乏完整的解决办法,或者解决办法不是很好,记录一下最后自己是怎么解决的。

vbnet 复制代码
PS:NEXT.JS的版本是14~

第一个报错: The "next export" command has been removed in favor of "output: export" in next.config.js

github actions提示是在Static HTML export with Next.js 阶段报错了,这时候我们查阅官网,发现next14导出静态资源时,不需要执行next export,而是修改next.config.js即可

lua 复制代码
//next.config.js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  output: 'export',
}
 
module.exports = nextConfig

因此可以在yml文件里删除以下两行代码:

vbnet 复制代码
- name: Static HTML export with Next.js
  run: ${{ steps.detect-package-manager.outputs.runner }} next export

参考链接: nextjs.org/docs/advanc...

nextjs.org/docs/pages/...

问题二:部署成功后,页面"白纸黑字",静态资源加载失败

在actions终于不报错后,我兴奋地打开了部署后的页面,发现只能看到"白纸黑字",发现静态资源没有加载出来。打开F12后发现请求的资源地址为 xxx.github.io/_next/stati... 直接去访问了我github仓库的根路径,而不是项目根路径。

这时候就需要去修改我们打包后的basePath,将打包后的基础路径配置为仓库名,这样静态资源在加载时,会在github的该仓库下进行查找。 (其实我一开始是只改了assetsPath,后面发现还是会影响favicon的加载,所以还是直接修改basePath吧)。

但是在本地开发环境时(localhost:3000)时,是不需要加前缀的,因此需多加一个node环境判断。不然路由会默认在app文件夹下找这个basePath名的文件夹,但是又找不到,导致页面返回404(具体可参考官网路由解析)

arduino 复制代码
//next.config.js
const isProd = process.env.NODE_ENV === "production";

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: "export",
  basePath : isProd ? "/repo-name" : "/",  
  images: {
    unoptimized: true,
  },
};

export default nextConfig;

结尾附上next.yml文件 (放置在.github/workflows路径下即可)

yaml 复制代码
# Sample workflow for building and deploying a Next.js site to GitHub Pages
#
# To get started with Next.js see: https://nextjs.org/docs/getting-started
#
name: Deploy Next.js site to Pages

on:
  # Runs on pushes targeting branch
  push:
    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

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
            echo "runner=yarn" >> $GITHUB_OUTPUT
            exit 0
          elif [ -f "${{ github.workspace }}/package.json" ]; then
            echo "manager=npm" >> $GITHUB_OUTPUT
            echo "command=ci" >> $GITHUB_OUTPUT
            echo "runner=npx --no-install" >> $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
        uses: actions/configure-pages@v4
      - name: Restore cache
        uses: actions/cache@v4
        with:
          path: |
            .next/cache
          # Generate a new cache whenever packages or source files change.
          key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}-${{ hashFiles('**.[jt]s', '**.[jt]sx') }}
          # If source files changed but packages didn't, rebuild from a prior cache.
          restore-keys: |
            ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}-
      - name: Install dependencies
        run: ${{ steps.detect-package-manager.outputs.manager }} ${{ steps.detect-package-manager.outputs.command }}
      - name: Build with Next.js
        run: ${{ steps.detect-package-manager.outputs.runner }} next build
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./out

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

希望对大家有所帮助~

相关推荐
gnip1 小时前
链式调用和延迟执行
前端·javascript
SoaringHeart1 小时前
Flutter组件封装:页面点击事件拦截
前端·flutter
杨天天.1 小时前
小程序原生实现音频播放器,下一首上一首切换,拖动进度条等功能
前端·javascript·小程序·音视频
Dragon Wu1 小时前
React state在setInterval里未获取最新值的问题
前端·javascript·react.js·前端框架
Jinuss1 小时前
Vue3源码reactivity响应式篇之watch实现
前端·vue3
YU大宗师1 小时前
React面试题
前端·javascript·react.js
木兮xg1 小时前
react基础篇
前端·react.js·前端框架
ssshooter2 小时前
你知道怎么用 pnpm 临时给某个库打补丁吗?
前端·面试·npm
IT利刃出鞘3 小时前
HTML--最简的二级菜单页面
前端·html
yume_sibai3 小时前
HTML HTML基础(4)
前端·html