跳到主要内容

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 与你的数据库 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 的用户界面将该命令添加到构建设置中。

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

Vercel project dashboard&#39;s Build Command setting

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

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

© . All rights reserved.