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

希望对大家有所帮助~

相关推荐
weixin-a1530030831619 分钟前
vue疑难解答
前端·javascript·vue.js
Bellafu6663 小时前
selenium 常用xpath写法
前端·selenium·测试工具
blackorbird6 小时前
Edge 浏览器 IE 模式成攻击突破口:黑客借仿冒网站诱导攻击
前端·edge
谷歌开发者7 小时前
Web 开发指向标 | Chrome 开发者工具学习资源 (一)
前端·chrome·学习
名字越长技术越强7 小时前
Chrome和IE获取本机ip地址
前端
天***88967 小时前
Chrome 安装失败且提示“无可用的更新” 或 “与服务器的连接意外终止”,Chrome 离线版下载安装教程
前端·chrome
半梦半醒*7 小时前
zabbix安装
linux·运维·前端·网络·zabbix
清羽_ls7 小时前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
你的人类朋友8 小时前
“签名”这个概念是非对称加密独有的吗?
前端·后端·安全
西陵8 小时前
Nx带来极致的前端开发体验——任务缓存
前端·javascript·架构