Next.js 集成 Prisma 遇.ts文件扩展名未知错误求助
Next.js + Prisma 遇到 .ts 文件扩展名未知错误
刚接触Next.js,尝试用Prisma ORM时碰到了问题,之前还遇到过无法在项目中使用模块的错误,现在尝试向数据库插入数据时触发了如下错误:
TypeError: Unknown file extension ".ts" for C:\Users\Username\Documents\Repositorios\resumos\src\app\api\hello\route.ts at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9) at defaultGetFormat (node:internal/modules/esm/get_format:203:36) at defaultLoad (node:internal/modules/esm/load:143:22) at async ModuleLoader.load (node:internal/modules/esm/loader:409:7) at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:291:45) at async link (node:internal/modules/esm/module_job:76:21) { code: 'ERR_UNKNOWN_FILE_EXTENSION' }
我的package.json配置:
{ "name": "teste", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@prisma/client": "^5.17.0", "@radix-ui/react-dropdown-menu": "^2.1.1", "@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-separator": "^1.1.0", "@radix-ui/react-slot": "^1.1.0", "class-variance-authority": "^0.7.0", "clsx": "^2.1.1", "lucide-react": "^0.411.0", "next": "14.2.5", "next-themes": "^0.3.0", "react": "^18", "react-dom": "^18", "tailwind-merge": "^2.4.0", "tailwindcss-animate": "^1.0.7" }, "devDependencies": { "@iconify/react": "^5.0.1", "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "14.2.5", "postcss": "^8", "prisma": "^5.17.0", "tailwindcss": "^3.4.1", "typescript": "^5" } }
tsconfig.json配置:
{ "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] }
解决建议
- 不要用
node命令直接运行API路由文件(比如route.ts),必须通过npm run dev启动Next.js服务,由Next.js处理TypeScript文件的编译和加载 - 检查代码中是否存在用
require()导入.ts文件的情况,Next.js 14使用ES模块,统一用import语法 - 清理项目缓存后重新安装依赖:
rm -rf .next node_modules package-lock.json npm install npm run dev - 确认Prisma Client的使用方式正确:在API路由中导入
@prisma/client时,确保是从正确路径导入,且没有在非Next.js托管的脚本中引用路由文件
内容的提问来源于stack exchange,提问作者João Marcos
相关产品推荐
相关产品推荐

