跳到主要內容

Netlify 構建依賴快取解決方案

問題

如果您將使用 Prisma ORM 的應用程式部署到 Netlify,您在部署時可能會遇到以下錯誤訊息

Prisma has detected that this project was built on Netlify, 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/netlify-build

發生此問題的原因是 Netlify 會快取您的專案依賴項,直到其中一個依賴項發生更改。它這樣做是為了加快構建速度,雖然這通常是件好事,但它給 Prisma Client 帶來了一些問題。

Prisma ORM 使用 postinstall 鉤子在安裝依賴項時生成 Prisma Client。由於 Netlify 使用快取模組,此 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 前置到現有的構建命令之前

{
...
"scripts" {
"build": "prisma generate && <actual-build-command>"
}
...
}

Netlify UI 的構建指令碼欄位

另一種在每次部署時執行 prisma generate 的方法是透過 Netlify 的 UI 將該命令新增到構建設定中。

在您的專案儀表板中,導航到“站點設定”選項卡並找到“構建與部署”部分。在該部分中,進入“持續部署”子部分。

在該部分中找到標有“構建設定”的框,然後單擊“編輯設定”按鈕

Netlify project dashboard&#39;s Build settings button

單擊該按鈕將開啟一個包含各種欄位的表單。找到“構建命令”欄位,並將 prisma generate 前置到現有指令碼之前

Netlify project dashboard&#39;s Build command setting filled

© . This site is unofficial and not affiliated with Prisma Data, Inc.