Node.js TypeScript项目中ERR_REQUIRE_ESM错误解决求助
TypeScript + Express 项目问题求助
问题描述
跟着TypeScript教程搭建Express项目,严格遵循步骤操作后遇到两个问题:
- 触发
ERR_REQUIRE_ESM错误,提示无法用require()导入ES模块nanoid,错误栈信息如下:
/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:851 return old(m, filename); ^ Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/nanoid/index.js from /Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/model/userModel.ts not supported. Instead change the require of index.js in /Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/model/userModel.ts to a dynamic import() which is available in all CommonJS modules. at Object.require.extensions.<computed> [as .js] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:851:20) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/model/userModel.ts:26:18) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/service/userService.ts:7:37) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/controller/userController.ts:13:23) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/routes/userRouter.ts:7:26) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/routes/index.ts:8:38) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/src/app.ts:11:34) at Module.m._compile (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:857:29) at Object.require.extensions.<computed> [as .ts] (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/index.js:859:16) at phase4 (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/bin.js:466:20) at bootstrap (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/bin.js:54:12) at main (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/bin.js:33:12) at Object.<anonymous> (/Users/oforduhh/Documents/EXPRESS JS/ts_api_auth/node_modules/ts-node/dist/bin.js:579:5) { code: 'ERR_REQUIRE_ESM' }
- 控制器无法调用
UserModel.create(body),控制器代码如下:
import { Request, Response } from "express"; import UserModel from "../model/userModel"; import { CreateUserInput } from "../schema/userSchema"; import log from "../utils/logger"; export const createUserHandler = async ( req: Request<{}, {}, CreateUserInput>, res: Response ) => { const body = req.body; try { const user = await UserModel.create(body); res.json({ message: "User created", status: true, data: user, }); } catch (error: any) { if (error.code === 11000) { return res.status(409).send("Account already exists"); } res.status(500).send("Internal server error"); log.error(error); } };
解决方案
针对 ERR_REQUIRE_ESM 错误(nanoid 导入问题)
- 方案1:降级nanoid到兼容CommonJS的版本
nanoid v4及以上为纯ESM模块,若项目是CommonJS环境,执行以下命令降级到v3.x:npm install nanoid@3 - 方案2:配置项目支持ESM
- 在
package.json中添加:"type": "module" - 修改
tsconfig.json:- 设置
"module": "ESNext" - 设置
"moduleResolution": "node16"或"nodenext"
- 设置
- 启动时使用
ts-node --esm,或替换为tsx运行项目
- 在
- 方案3:改用动态导入
在userModel.ts中把静态require改为动态import(需放在async函数内或使用顶层await):// 示例:在需要使用nanoid的async函数内 async function generateId() { const { nanoid } = await import('nanoid'); return nanoid(); }
针对 UserModel.create(body) 调用问题
- 检查UserModel定义
确保userModel.ts正确导出Mongoose模型:import mongoose from 'mongoose'; const UserSchema = new mongoose.Schema({ // 你的字段定义,比如email、password等 }); const UserModel = mongoose.model('User', UserSchema); export default UserModel; - 验证输入类型匹配
确认CreateUserInput的结构和UserSchema的字段完全匹配,避免类型不兼容导致的隐性错误 - 确保输入验证通过
如果使用Zod等工具做输入验证,在调用create前先执行CreateUserInput.parse(req.body),确保body符合要求
内容的提问来源于stack exchange,提问作者Harrison Ofordu
相关产品推荐
相关产品推荐

