SuperAPI AI 工具集

prisma-upgrade-v7-esm-support

编程与开发

查看项目

更新于 10-16 04:12

技能介绍

用途

该技能是 Prisma ORM v7 的 ESM 支持参考文档。Prisma ORM v7 仅以 ES 模块(ESM)形式发布,因此使用该功能时,项目必须配置为 ESM。本文档用于指导完成相关配置与迁移。

主要能力

文档围绕 ESM 迁移提供以下参考内容:

  • 必要配置变更:package.json 与 tsconfig.json 的调整方式。
  • 导入语法变更:命名导入的写法,以及文件扩展名的处理规则。
  • 最低版本要求:Node.js 与 TypeScript 的最低版本。
  • CommonJS 兼容方案:在必须使用 CommonJS 时的替代做法。
  • 框架与工具适配:Next.js、Express、Jest 的配置方式。
  • 故障排查:常见报错的原因与处理方向。

使用方式

package.json

添加 type 字段:

{
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

tsconfig.json

配置为 ESM:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "bundler",
    "target": "ES2023",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "outDir": "dist"
  },
  "include": ["src/**/*", "prisma/**/*"]
}

替代方案:Node16/NodeNext

{
  "compilerOptions": {
    "module": "Node16",
    "moduleResolution": "Node16",
    "target": "ES2022"
  }
}

导入语法变更

命名导入:

// ESM (v7)
import { PrismaClient } from '../generated/client'

// Not: require()

文件扩展名:

  • 当 moduleResolution 为 "Node16" 时,需添加 .js 扩展名:
import { helper } from './utils/helper.js'
  • 当 moduleResolution 为 "bundler" 时,扩展名可选。

最低版本要求

要求 最低版本
Node.js 20.19.0
TypeScript 5.4.0

CommonJS 兼容

如果必须使用 CommonJS,可采用以下方式。

动态导入:

// CommonJS file
async function main() {
  const { PrismaClient } = await import('../generated/client.js')
  const prisma = new PrismaClient()
}

单独的 ESM 文件(创建 ESM 包装器):

// prisma.mjs
import { PrismaClient } from '../generated/client'
export const prisma = new PrismaClient()

框架注意事项

Next.js:Next.js 支持 ESM。确保将 next.config.js 改为 next.config.mjs:

// next.config.mjs
export default {
  // config
}

Express:更新入口点:

// index.js (with "type": "module")
import express from 'express'
import { PrismaClient } from '../generated/client'

const app = express()
const prisma = new PrismaClient()

Jest:为 ESM 配置 Jest:

{
  "jest": {
    "preset": "ts-jest/presets/default-esm",
    "extensionsToTreatAsEsm": [".ts"],
    "transform": {
      "^.+\\.tsx?$": ["ts-jest", { "useESM": true }]
    }
  }
}

或者使用原生支持 ESM 的 Vitest。

故障排查

  • "ERR_REQUIRE_ESM":代码对 ESM 模块使用了 require(),应改用 import。
  • "Cannot use import statement outside a module":在 package.json 中添加 "type": "module"。
  • TypeScript 编译错误:确保 tsconfig.json 中的 module 与 moduleResolution 设置正确。

适用场景

适用于正在使用或计划升级到 Prisma ORM v7、需要将项目配置为 ESM 的开发者,包括使用 Next.js、Express 等框架以及 Jest、Vitest 等测试工具的项目。

限制

Prisma ORM v7 仅以 ES 模块形式发布,项目必须配置为 ESM。若必须使用 CommonJS,需采用动态导入或单独的 ESM 包装文件等兼容方案。Node.js 最低版本为 20.19.0,TypeScript 最低版本为 5.4.0。