跳到主要内容

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 hook 在安装依赖时生成 Prisma Client。由于 Vercel 使用缓存模块,这个 postinstall hook 在首次部署之后的后续部署中不会运行。这导致 Prisma Client 与你的数据库 schema 不同步。

此错误消息会阻止这种情况发生,并引导你来此处了解如何解决根本问题。

低于 4.13.0 的 Prisma Client 版本

在低于 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 将命令添加到构建设置中。

在你的项目仪表板中,转到“设置”选项卡,找到“通用”部分。在该部分中,你会看到一个标有“构建与开发设置”的框,其中包含一个名为“构建命令”的输入字段

Vercel project dashboard&#39;s Build Command setting

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

Vercel project dashboard&#39;s Build Command setting filled