使用 Nuxt Prisma 模块
Nuxt Prisma 模块简化了 Prisma ORM 与 Nuxt 应用的集成。
¥The Nuxt Prisma module simplifies the integration of Prisma ORM into your Nuxt applications.
Prisma ORM 是一个数据库库,可让你对数据库模式进行建模,提供自动生成的迁移,并允许你以直观和类型安全的方式查询数据库。
¥Prisma ORM is a database library that lets you model your database schema, provides auto-generated migrations and lets you query the database in an intuitive and type-safe way.
此模块提供了多种功能,可简化 Nuxt 应用中 Prisma ORM 的设置和使用,从而更轻松地与数据库交互。
¥This module provides several features to streamline the setup and usage of Prisma ORM in a Nuxt application, making it easier to interact with your database.
特性
¥Features
-
项目初始化:在你的 Nuxt 项目中自动设置一个带有 SQLite 数据库的 Prisma ORM 项目。
¥Project initialization: Automatically sets up a Prisma ORM project with a SQLite database within your Nuxt project.
-
可组合:提供自动导入的
usePrismaClient()
可组合项,供你在 Vue 文件中使用。¥Composable: Provides an auto-imported
usePrismaClient()
composable for use in your Vue files. -
API 路由集成:自动导入
PrismaClient
的实例以用于 API 路由来查询你的数据库。¥API route integration: Automatically imports an instance of
PrismaClient
for use in API routes to query your DB. -
Prisma Studio 访问:允许通过 Nuxt Devtools 访问 Prisma Studio,以查看和手动编辑数据。
¥Prisma Studio access: Enables access to Prisma Studio through Nuxt Devtools for viewing and manually editing data.
入门
¥Getting started
-
创建 新的 Nuxt 项目:
¥Create a new Nuxt Project:
npm create nuxt test-nuxt-app
-
导航到项目目录并使用 Nuxt CLI 安装
@prisma/nuxt
:¥Navigate to project directory and install
@prisma/nuxt
using the Nuxt CLI:cd test-nuxt-app
npx nuxi@latest module add @prisma/nuxt
警告如果你正在使用
pnpm
,请确保提升 Prisma 依赖。请按照 Prisma 工作室步骤 获取详细说明。¥If you're using
pnpm
, make sure to hoist Prisma dependencies. Follow the Prisma studio steps for detailed instructions. -
启动开发服务器:
¥Start the development server:
npm run dev
启动开发服务器将:
¥Starting the development server will:
-
自动安装 Prisma CLI
¥Automatically install the Prisma CLI
-
使用 SQLite 初始化 Prisma 项目
¥Initialize a Prisma project with SQLite
-
在 Prisma Schema 文件中创建
User
和Post
示例模型:¥Create an
User
andPost
example model in the Prisma Schema file:prisma/schema.prisma// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
} -
提示你运行迁移以使用 Prisma 迁移 创建数据库表
¥Prompt you to run a migration to create database tables with Prisma Migrate
note如果没有
migrations
文件夹,数据库会在你第一次启动模块时自动迁移。之后,你需要在 CLI 中手动运行npx prisma migrate dev
以应用任何架构更改。手动运行npx prisma migrate dev
命令可以更轻松、更安全地管理迁移,还可以 troubleshoot 任何与迁移相关的错误。¥The database migrates automatically the first time you start the module if there isn't a
migrations
folder. After that, you need to runnpx prisma migrate dev
manually in the CLI to apply any schema changes. Running thenpx prisma migrate dev
command manually makes it easier and safer to manage migrations and also to troubleshoot any migration-related errors. -
安装并生成 Prisma 客户端,使你能够查询你的数据库
¥Install and generate a Prisma Client which enables you to query your DB
-
自动启动 Prisma 工作室
¥Automatically start Prisma Studio
-
-
你现在可以在项目中使用 Prisma ORM。如果你接受了添加 Prisma Studio 的提示,则可以通过 Nuxt Devtools 访问 Prisma Studio。查看 使用部分 以了解如何在你的应用中使用 Prisma Client。
¥You can now use Prisma ORM in your project. If you accepted the prompt to add Prisma Studio, you can access Prisma Studio through the Nuxt Devtools. See the usage section to learn how to use Prisma Client in your app.
使用不同的数据库提供商
¥Using a different database provider
@prisma/nuxt
模块可与任何 Prisma ORM 支持的数据库提供程序 一起使用。你可以将 入门示例 配置为使用你选择的数据库。对于 没有现有数据的数据库 和 具有预先存在数据的数据库,步骤会有所不同。
¥The @prisma/nuxt
module works with any database provider that Prisma ORM supports. You can configure the getting started example to use a database of your choice. The steps would be different for a database without existing data and a database with pre-existing data.
使用没有现有数据的数据库
¥Using a database without existing data
要将 入门示例 配置为使用没有任何现有数据的 PostgreSQL 数据库:
¥To configure the getting started example to use a PostgreSQL database without any existing data:
-
停止 Nuxt 开发服务器和 Prisma Studio(如果它们仍在运行):
¥Stop the Nuxt development server and Prisma Studio (if they are still running):
npx kill-port 3000 # Stops Nuxt dev server (default port)
npx kill-port 5555 # Stops Prisma Studio (default port) -
导航到
schema.prisma
文件并更新datasource
块以指定postgresql
提供程序:¥Navigate to the
schema.prisma
file and update thedatasource
block to specify thepostgresql
provider:prisma/schema.prisma// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
} -
使用 PostgreSQL 数据库 URL 更新
.env
文件中的DATABASE_URL
环境变量:¥Update the
DATABASE_URL
environment variable in the.env
file with your PostgreSQL database URL:.env## This is a sample database URL, please use a valid URL
DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample" -
删除 SQLite 数据库文件和迁移文件夹:
¥Delete the SQLite database file and the migrations folder:
rm prisma/dev.db # Delete SQLite database file
rm -r prisma/migrations # Delete the pre-existing migrations folder -
运行开发服务器:
¥Run the development server:
npm run dev
启动开发服务器将提示你将架构更改迁移到数据库,你应该同意。然后同意提示,从 Nuxt Devtools 安装和访问 Prisma Studio。
¥Starting the development server will prompt you to migrate the schema changes to the database, to which you should agree. Then agree to the prompt to install and access Prisma Studio from the Nuxt Devtools.
-
@prisma/nuxt
模块已准备好与你的 PostgreSQL 数据库一起使用。查看 使用部分 以了解如何在你的应用中使用 Prisma Client。¥The
@prisma/nuxt
module is ready to use with your PostgreSQL database. See the usage section to learn how to use Prisma Client in your app.
使用具有预先存在数据的数据库
¥Using a database with pre-existing data
要将 入门示例 配置为使用其中已有数据的 PostgreSQL 数据库:
¥To configure the getting started example to use a PostgreSQL database that already has data in it:
-
停止开发服务器和 Prisma Studio(如果它们仍在运行):
¥Stop the dev server and Prisma Studio (if they are still running):
// stops Nuxt dev server from running incase it's still running
npx kill-port 3000
// stops Prisma Studio instance incase it's still running
npx kill-port 5555 -
删除 Prisma 文件夹:
¥Delete the Prisma folder:
rm -r prisma/
-
使用 PostgreSQL 数据库 URL 更新
.env
文件中的DATABASE_URL
环境变量:¥Update the
DATABASE_URL
environment variable in the.env
file with your PostgreSQL database URL:.env## This is a sample database URL, please use a valid URL
DATABASE_URL="postgresql://janedoe:mypassword@localhost:5432/mydb?schema=sample" -
要从现有数据库生成 Prisma Schema 和迁移文件夹,你必须 introspect 数据库。从 自省指南 完成步骤 1 到步骤 4 并继续。
¥To generate a Prisma Schema and migrations folder from the existing database, you have to introspect the database. Complete step 1 to step 4 from the introspection guide and continue.
-
启动开发服务器将跳过将架构更改迁移到数据库的提示,因为迁移文件夹已经存在。同意提示从 Nuxt Devtools 安装和访问 Prisma Studio。
¥Starting the development server will skip the prompt to migrate the schema changes to the database, as the migrations folder already exists. Agree to the prompt to install and access Prisma Studio from the Nuxt Devtools.
-
@prisma/nuxt
模块已准备好与你的 PostgreSQL 数据库一起使用。查看 使用部分 以了解如何在你的应用中使用 Prisma Client。¥The
@prisma/nuxt
module is ready to be used with your PostgreSQL database. See the usage section to learn how to use Prisma Client in your app.
用法
¥Usage
选项 A:usePrismaClient
可组合项
¥Option A: usePrismaClient
composable
在你的 Nuxt 服务器组件中使用可组合项
¥Using the composable in your Nuxt server component
如果你使用 Nuxt 服务器组件,则可以使用 Prisma Client 的全局实例在你的 .server.vue
文件中:
¥If you're using Nuxt server components, you can use the global instance of the Prisma Client in your .server.vue
files:
<script setup>
const prisma = usePrismaClient()
const user = await prisma.user.findFirst()
</script>
<template>
<p>{{ user.name }}</p>
</template>
选项 B:lib/prisma.ts
¥Option B: lib/prisma.ts
运行初始设置提示后,此模块将创建包含 Prisma Client 全局实例的 lib/prisma.ts
文件。
¥After running through the initial setup prompts, this module creates the lib/prisma.ts
file which contains a global instance of Prisma Client.
import { PrismaClient } from '@prisma/client'
const prismaClientSingleton = () => {
return new PrismaClient()
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma
你可以通过在 lib/prisma.ts
文件中使用客户端扩展来自定义 Prisma Client 的功能。这是一个使用 加速客户端扩展 的示例:
¥You can customize Prisma Client's capabilities by using client extensions in your lib/prisma.ts
file. Here is an example using the Accelerate client extension:
import { PrismaClient } from '@prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'
const prismaClientSingleton = () => {
return new PrismaClient().$extends(withAccelerate())
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma
如果你想利用使用 Prisma 客户端扩展 的客户端,请使用 lib
文件夹中的 prisma
实例。
¥Use the prisma
instance from the lib
folder if you want to leverage a client using Prisma Client extensions.
在你的 API 路由中使用全局 Prisma 客户端实例
¥Using the global Prisma Client instance in your API route
你可以在 Nuxt API 路由中使用 Prisma Client 的全局实例,如下所示:
¥You can use the global instance of the Prisma Client in your Nuxt API route as follows:
import prisma from "~/lib/prisma";
export default defineEventHandler(async (event) => {
return {
user: await prisma.user.findFirst(),
};
});
在你的 Nuxt 服务器组件中使用全局 Prisma 客户端实例
¥Using the global Prisma Client instance in your Nuxt server component
如果你使用 Nuxt 服务器组件,则可以使用 Prisma Client .server.vue
文件的全局实例:
¥If you're using Nuxt server components, you can use the global instance of the Prisma Client .server.vue
files:
<script setup>
import prisma from '~/lib/prisma';
const user = await prisma.user.findFirst()
</script>
<template>
<p>{{ user.name }}</p>
</template>
配置
¥Configuration
你可以使用 nuxt.config.ts
中的 prisma
键配置 @prisma/nuxt
模块:
¥You can configure the @prisma/nuxt
module by using the prisma
key in nuxt.config.ts
:
export default defineNuxtConfig({
// ...
prisma: {
// Options
}
})
通过运行 npm run dev
成功设置模块后,prisma
密钥在 nuxt.config.ts
中可用
¥The prisma
key is available in nuxt.config.ts
after successfully setting up the module by running npm run dev
选项 | 类型 | 默认 | 描述 |
---|---|---|---|
installCLI | boolean | true | 是否安装 Prisma CLI。 |
installClient | boolean | true | 是否在项目中安装 Prisma 客户端 库。 |
generateClient | boolean | true | 是否 generate PrismaClient 实例。每次运行时执行 npx prisma generate 以根据模式更改更新客户端。 |
formatSchema | boolean | true | 是否 format Prisma 模式 文件。 |
installStudio | boolean | true | 是否在 Nuxt Devtools 中安装并启动 Prisma 工作室。 |
autoSetupPrisma | boolean | false | 是否在设置过程中跳过所有提示。此选项对于在脚本或 CI/CD 管道中自动设置 Prisma 很有用。 |
skipPrompts | false | false | 跳过所有提示 |
prismaRoot | string | false | 使用 Nuxt 层 时需要。例如,如果你有一个名为 database 的 Nuxt 层,则 prismaRoot 在基本 nuxt 配置中将是 ./database 。这指的是将初始化或检查 Prisma 的文件夹。 |
prismaSchemaPath | string | undefined | 使用 Nuxt 层 时需要。例如,如果你有一个名为 database 的 Nuxt 层,则 prismaSchemaPath 在基本 nuxt 配置中将是 ./database/prisma/schema.prisma 。 |
runMigration | boolean | true | 是否自动运行 Prisma 迁移。如果你使用的是 MongoDB 或 PlanetScale,请使用 npx prisma db push 命令。这些数据库不支持迁移,因此此命令将确保你的架构得到适当更新。 |
局限性
¥Limitations
PrismaClient
构造函数选项在 usePrismaClient
可组合项中不可配置
¥PrismaClient
constructor options are not configurable in the usePrismaClient
composable
usePrismaClient
模块目前不允许配置 PrismaClient
构造函数选项。
¥The usePrismaClient
module does not currently allow for configuration of PrismaClient
constructor options.
边缘运行时不支持 usePrismaClient
可组合项
¥The usePrismaClient
composable is not supported in edge runtimes
usePrismaClient
可组合项当前依赖于在边缘运行时不起作用的 PrismaClient
实例。如果你需要可组合项的边缘支持,请在 Discord 或 GitHub 上告知我们。
¥The usePrismaClient
composable currently relies on a PrismaClient
instance that does not work in edge runtimes. If you require edge support for the composable, please let us know on Discord or GitHub.
故障排除
¥Troubleshooting
Prisma Studio 无法使用 pnpm
打开
¥Prisma Studio not opening with pnpm
如果在使用 pnpm
时遇到以下错误,并且 Prisma Studio 无法打开:
¥If you're encountering the following error when using pnpm
and Prisma Studio isn't opening:
Uncaught SyntaxError: The requested module '/_nuxt/node_modules/.pnpm/*@*/node_modules/@prisma/client/index-browser.js?v=' does not provide an export named 'PrismaClient' (at plugin.mjs?v=*)
要解决此问题,请在项目根目录中创建一个 .npmrc
文件,并添加以下配置以提升 Prisma 依赖:
¥To resolve this issue, create a .npmrc
file in your project root and add the following configuration to hoist Prisma dependencies:
hoist-pattern[]=*prisma*
这将确保 Prisma 依赖由 pnpm
正确解析。
¥This will ensure that Prisma dependencies are properly resolved by pnpm
.
解决 TypeError: Failed to resolve module specifier ".prisma/client/index-browser"
¥Resolving TypeError: Failed to resolve module specifier ".prisma/client/index-browser"
如果在构建和预览应用后,在浏览器控制台中遇到以下错误消息:
¥If you encounter the following error message in the browser console after building and previewing your application:
TypeError: Failed to resolve module specifier ".prisma/client/index-browser"
要解决此问题,请将以下配置添加到你的 nuxt.config.ts 文件中:
¥To resolve this issue, add the following configuration to your nuxt.config.ts file:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
modules: [
'@prisma/nuxt',
],
// additional config
vite: {
resolve: {
alias: {
'.prisma/client/index-browser': './node_modules/.prisma/client/index-browser.js',
},
},
},
})
此配置可确保模块说明符正确映射到相应的文件。
¥This configuration ensures that the module specifier is correctly mapped to the appropriate file.
包管理器支持的限制
¥Limitations in package manager support
该模块旨在与流行的包管理器配合使用,包括 npm、Yarn 和 pnpm。但是,从 v0.2
开始,由于导致无限期安装循环的问题,它与 Bun 不完全兼容。
¥The module is designed to work with popular package managers, including npm, Yarn, and pnpm. However, as of v0.2
, it is not fully compatible with Bun due to an issue causing an indefinite installation loop.
此外,此包尚未使用 Deno 进行测试,因此不受官方支持。
¥Additionally, this package has not been tested with Deno and is therefore not officially supported.
解决 Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
¥Resolving Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
即使你已生成客户端,如果仍然遇到以下消息。
¥If you encounter the following message even if you have generated the client.
Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
请尝试删除 schema.prisma 中的 output = ../generated/prisma
,例如:
¥Please try delete output = ../generated/prisma
in schema.prisma, like
generator client {
provider = "prisma-client-js"
}
当你为 Prisma 客户端指定自定义输出目录时,这意味着生成的客户端代码将不会位于默认的 node_modules/@prisma/client directory
目录中。它将在你项目的根目录下的 generated/prisma/
下生成。但是,Nuxt 中的 @prisma/nuxt
模块期望在默认的 @prisma/client
位置找到 PrismaClient
。
¥When you specify a custom output directory for the Prisma Client, it means that the generated client code will not be located in the default node_modules/@prisma/client directory
. Instead, it will be generated in your project's root directory under generated/prisma/
. However, the @prisma/nuxt
module in Nuxt expects to find PrismaClient
in the default @prisma/client
location.
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.