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

希望对大家有所帮助~

相关推荐
小白小白从不日白17 分钟前
react hooks--useCallback
前端·react.js·前端框架
恩婧25 分钟前
React项目中使用发布订阅模式
前端·react.js·前端框架·发布订阅模式
mez_Blog26 分钟前
个人小结(2.0)
前端·javascript·vue.js·学习·typescript
珊珊而川34 分钟前
【浏览器面试真题】sessionStorage和localStorage
前端·javascript·面试
森叶1 小时前
Electron 安装包 asar 解压定位问题实战
前端·javascript·electron
drebander1 小时前
ubuntu 安装 chrome 及 版本匹配的 chromedriver
前端·chrome
软件技术NINI1 小时前
html知识点框架
前端·html
深情废杨杨1 小时前
前端vue-插值表达式和v-html的区别
前端·javascript·vue.js
GHUIJS1 小时前
【vue3】vue3.3新特性真香
前端·javascript·vue.js
markzzw1 小时前
我在 Thoughtworks 被裁前后的经历
前端·javascript·面试