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 的使用者介面將該命令新增到構建設定中。
在你的專案儀表板中,轉到設定選項卡,找到通用部分。在該部分中,你會找到一個名為構建與開發設定的框,其中包含一個名為構建命令的輸入欄位。

在該欄位中,將 `prisma generate` 新增到現有指令碼之前
