第四部分:构建与部署

4.1 构建静态网站

npm run build

构建产物输出到 output/ 目录。

4.2 预览构建结果

npm start

访问 http://localhost:3000 验证构建结果。

4.3 部署平台选择

平台 特点 推荐场景
GitHub Pages 免费,GitHub集成 GitHub用户
Vercel Next.js官方,部署快 快速部署
Netlify 功能丰富,UI友好 功能需求
Cloudflare Pages 全球CDN,速度快 性能优先

4.4 部署到 Vercel

步骤

  1. 访问 vercel.com,用 GitHub 登录
  2. 点击 "Add New" → "Project"
  3. 选择仓库,点击 "Import"
  4. 关键配置
    • Output Directory: output
  5. 添加环境变量
  6. 点击 "Deploy"

环境变量

确保设置 NEXT_PUBLIC_SITE_URL 为 Vercel 提供的 URL。

4.5 部署到 GitHub Pages

GitHub Actions 自动部署

创建 .github/workflows/deploy.yml

name: Deploy to GitHub Pages
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "20"
      - run: npm ci
      - run: npm run build
        env:
          NEXT_PUBLIC_SITE_URL: https://username.github.io
      - uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./output

在仓库 Settings → Pages 中,Source 选择 "GitHub Actions"。

4.6 部署到 Netlify

  1. 访问 netlify.com
  2. 导入 GitHub 仓库
  3. 配置:
    • Build command: npm run build
    • Publish directory: output
  4. 添加环境变量
  5. 部署

4.7 部署到 Cloudflare Pages

  1. 访问 dash.cloudflare.com
  2. 进入 "Workers & Pages"
  3. 创建 Pages 项目
  4. 连接 GitHub 仓库
  5. 配置:
    • Build command: npm run build
    • Build output directory: output
  6. 添加环境变量
  7. 部署

4.8 自定义域名

各平台均支持自定义域名,在平台设置中配置即可。