🚀 React Router 7 + Vercel 部署全指南

60 阅读2分钟

一、 开发环境准备 (本地)

  1. 推荐包管理器:使用 pnpm 替代 npm 以获得更快的构建速度和更清晰的依赖管理。

如果已经使用npm构建,那么先删掉node_modules文件夹,安装pnpm

pnpm install
  1. Node.js 版本限制

package.json 中显式指定:

    • JSON
"engines": { "node": "20.x" }
  1. 静态模式配置 (SPA)

若不需要 SSR(服务端渲染),在 react-router.config.ts 中设置:

    • TypeScript
export default { ssr: false } satisfies Config;
  1. 关联github及vercel

本地代码提交到github,同时登录vercel平台,将vercel与github关联上,后续你在本地改动了代码并提交到github后,访问vercel平台的项目域名就能看到改动的内容了


二、 静态资源与图标 (Icon)

  1. 文件存放:所有的图片、SVG 图标必须放在根目录的 public/ 文件夹下。
  2. 页面引入

app/root.tsxlinks 函数中配置:

    • TypeScript
export const links: LinksFunction = () => [
  { rel: "icon", type: "image/svg+xml", href: "/logo.svg" },
];

三、 Vercel 部署关键点 (最重要)

如果你遇到 now-phpFunction Runtimes 报错,请检查以下配置:

vercel.json 配置(强制静态重写,防止 404):

  1. JSON
{
  "framework": "vite",
  "rewrites": [{ "source": "/(.*)", "destination": "/" }]
}
  1. Vercel 后台设置
    • Framework Preset: 优先选择 Vite;如果被锁定为 React Router,请确保手动开启 Build and Output Settings
    • Build Command: pnpm build
    • Output Directory: dist(如果在脚本中手动移动了产物)或 build/client
    • Install Command: pnpm install

四、 自定义域名

  1. 修改 Vercel 默认域名
    • Settings -> Domains -> Edit,可以直接修改 xxx.vercel.app 的前缀。
  1. 绑定独立域名
    • Domains 页面输入你购买的域名。
    • DNS 配置
      • A 记录:指向 76.76.21.21
      • CNAME 记录:指向 cname.vercel-dns.com

💡 核心避坑心得

  • 清理缓存:部署报错时,尝试删除 Vercel 项目重新导入,并确保 pnpm-lock.yaml 是最新的。
  • 路径大小写:Vercel 的 Linux 环境对文件名大小写敏感,确保 import 路径与文件名完全一致。