目录

Next.js 项目部署到 GitHub Pages 完整指南

2 分钟阅读技术

将 Next.js 项目部署到 GitHub Pages 是一个经济实惠的选择,特别适合个人博客和项目展示。

配置要求

首先,确保你的 next.config.js 正确配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',        // 必须设置为 export
  basePath: '/your-repo-name',  // 仓库名称
  images: {
    unoptimized: true,     // GitHub Pages 不支持图片优化
  },
}

module.exports = nextConfig;

项目设置

1. 更新 package.json

添加部署脚本:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "deploy": "gh-pages -d out"
  }
}

2. 安装 gh-pages

npm install --save-dev gh-pages

3. 配置 GitHub Actions

创建 .github/workflows/deploy.yml

name: Deploy to GitHub Pages

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build project
        run: npm run build

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./out

部署步骤

1. 创建 GitHub 仓库

在 GitHub 上创建一个新的仓库,命名为 your-username.github.io(用于个人页面)或任意名称(用于项目页面)。

2. 初始化 Git

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/your-username/your-repo-name.git

3. 推送到 GitHub

git push -u origin main

4. 等待部署

推送后,GitHub Actions 会自动构建并部署你的网站。你可以在仓库的 Actions 标签页查看进度。

常见问题解决

问题1:404 错误

原因: basePath 配置错误或路由问题 解决:

  • 确保 basePath 与仓库名称一致
  • 检查 next.config.js 配置

问题2:样式丢失

原因: CSS 文件路径问题 解决:

  • 使用 next/image 组件处理图片
  • 确保静态资源放在 public 目录

问题3:部署失败

原因: 依赖或构建问题 解决:

  • 检查 Actions 日志
  • 确保本地 npm run build 成功
  • 查看 Node.js 版本兼容性

优化建议

性能优化

  • 使用 next/image 优化图片
  • 实现代码分割
  • 启用 Gzip 压缩

SEO 优化

  • 添加 robots.txt
  • 创建 sitemap.xml
  • 配置 meta 标签

用户体验

  • 添加 PWA 支持
  • 实现离线功能
  • 优化加载状态

总结

通过以上步骤,你的 Next.js 项目就可以成功部署到 GitHub Pages。这种方法免费、简单,且自动化程度高。

如果你遇到任何问题,欢迎在评论区讨论!