Vercel 构建依赖缓存解决方案
问题
如果您使用 Prisma ORM 将应用程序部署到 Vercel,您可能会在部署时遇到以下错误消息
Prisma has detected that this project was built on Vercel, which caches dependencies.
This leads to an outdated Prisma Client because Prisma's auto-generation isn't triggered.
To fix this, make sure to run the `prisma generate` command during the build process.
Learn how: https://pris.ly/d/vercel-build
出现此问题的原因是 Vercel 会缓存您项目的依赖项,直到其中一个依赖项发生更改。这样做是为了加快构建速度,虽然这通常是件好事,但它给 Prisma Client 带来了一些问题。
Prisma ORM 使用 postinstall 钩子在安装依赖项时生成 Prisma Client。由于 Vercel 使用缓存模块,因此在首次部署之后的后续部署中,此 postinstall 钩子永远不会运行。这导致 Prisma Client 与您的数据库模式不同步。
此错误消息可防止这种情况发生,并引导您在此处了解如何修复根本问题。
Prisma Client 版本低于 4.13.0
在低于 4.13.0 的 Prisma Client 版本上,您可能会遇到类似以下的错误消息
// 1: When adding a field:
Unknown arg `name` in data.name for type UserCreateInput. Did you mean `nick`?
// 2: When removing a field:
Invalid `prisma.user.create()` invocation: The column `User.name` does not exist in the current database.
// 3: When a model was removed/renamed
Invalid `prisma.user.deleteMany()` invocation: The table `public.User` does not exist in the current database.
// 4: When a model was added
Cannot read properties of undefined (reading 'create')
本指南中描述的解决方案旨在解决这些问题。
解决方案
此问题可以通过在每次部署时显式生成 Prisma Client 来解决。在每次部署之前运行 prisma generate 将确保 Prisma Client 是最新的。
您可以通过多种不同方式配置部署以运行此命令
自定义 postinstall 脚本
这是首选方法,因为它是一个通用解决方案。
在项目 package.json 文件的 scripts 部分中,如果尚未有名为 postinstall 的脚本,请添加一个并向该脚本添加 prisma generate
{
...
"scripts" {
"postinstall": "prisma generate"
}
...
}
package.json 中的应用程序 build 脚本
在项目 package.json 文件的 scripts 部分中,在 build 脚本中,将 prisma generate 添加到默认的 vercel build 命令前面
{
...
"scripts" {
"build": "prisma generate && <actual-build-command>"
}
...
}
Vercel UI 的构建脚本字段
另一种配置 prisma generate 以在每次部署时运行的方法是通过 Vercel 的 UI 将命令添加到构建设置中。
在项目仪表板中,转到Settings选项卡并找到General部分。在该部分中,您会找到一个标有Build & Development Settings的框,其中包含一个名为Build Command的输入字段

在该字段中,将 prisma generate 添加到现有脚本前面
