解决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

希望对大家有所帮助~

相关推荐
小胖霞1 分钟前
全栈系列(15)github Actions自动化部署前端vue
前端·node.js·github
未来魔导2 分钟前
基于 Gin 框架的 大型 Web 项目推荐架构目录结
前端·架构·gin
foundbug99925 分钟前
Modbus协议C语言实现(易于移植版本)
java·c语言·前端
Luna-player25 分钟前
在前端中list.map的用法
前端·数据结构·list
用户479492835691529 分钟前
面试官问 React Fiber,这一篇文章就够了
前端·javascript·react.js
小徐_233340 分钟前
Gemini 3做粒子交互特效很出圈?拿 TRAE SOLO 来实现一波!
前端·ai编程·trae
LYFlied41 分钟前
【一句话概述】Webpack、Vite、Rollup 核心区别
前端·webpack·node.js·rollup·vite·打包·一句话概述
reddingtons1 小时前
PS 参考图像:线稿上色太慢?AI 3秒“喂”出精细厚涂
前端·人工智能·游戏·ui·aigc·游戏策划·游戏美术
一水鉴天1 小时前
整体设计 定稿 之23+ dashboard.html 增加三层次动态记录体系仪表盘 之2 程序 (Q199 之2) (codebuddy)
开发语言·前端·javascript
刘发财1 小时前
前端一行代码生成数千页PDF,dompdf.js新增分页功能
前端·typescript·开源