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

希望对大家有所帮助~

相关推荐
m0_748247552 小时前
Web 应用项目开发全流程解析与实战经验分享
开发语言·前端·php
m0_748255022 小时前
前端常用算法集合
前端·算法
真的很上进3 小时前
如何借助 Babel+TS+ESLint 构建现代 JS 工程环境?
java·前端·javascript·css·react.js·vue·html
web130933203983 小时前
vue elementUI form组件动态添加el-form-item并且动态添加rules必填项校验方法
前端·vue.js·elementui
NiNg_1_2343 小时前
Echarts连接数据库,实时绘制图表详解
前端·数据库·echarts
如若1234 小时前
对文件内的文件名生成目录,方便查阅
java·前端·python
滚雪球~5 小时前
npm error code ETIMEDOUT
前端·npm·node.js
沙漏无语5 小时前
npm : 无法加载文件 D:\Nodejs\node_global\npm.ps1,因为在此系统上禁止运行脚本
前端·npm·node.js
supermapsupport5 小时前
iClient3D for Cesium在Vue中快速实现场景卷帘
前端·vue.js·3d·cesium·supermap
brrdg_sefg5 小时前
WEB 漏洞 - 文件包含漏洞深度解析
前端·网络·安全