TypeScript+nodemon+ts-node使用node-fetch v3报ERR_REQUIRE_ESM解决方案
问题核心原因
node-fetch v3 起仅支持 ESM 模块规范,不支持 CommonJS 规范的 require 引入,是触发 ERR_REQUIRE_ESM 报错的根本原因。你可以根据项目需求选择以下两种配置方案:
方案1:全ESM模式(适配node-fetch v3原生规范,推荐)
package.json 配置
{ "type": "module", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "nodemon --esm index.ts" }, "dependencies": { "express": "^4.18.2", "json-server": "^0.17.4", "node-fetch": "^3.3.2" }, "devDependencies": { "@types/express": "^4.17.21", "@types/json-server": "^0.14.4", "@types/node": "^20.11.0", "@types/node-fetch": "^2.6.10", "nodemon": "^3.0.2", "ts-node": "^10.9.2", "typescript": "^5.3.3" } }
tsconfig.json 配置
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "skipLibCheck": true, "strict": true, "outDir": "./dist" }, "ts-node": { "experimentalSpecifierResolution": "node", "esm": true }, "include": ["index.ts"] }
执行命令
- 生产编译运行:
npm run build && npm run start - 开发模式运行:
npm run dev
方案2:CommonJS兼容模式(无需修改现有模块规范)
直接降级使用支持CommonJS的node-fetch v2版本,不需要调整项目模块规则:
- 先安装对应依赖:
npm install node-fetch@2 npm install @types/node-fetch@2 -D
- package.json 不需要添加
"type": "module"字段,其余依赖和scripts可保留原有配置 - tsconfig.json 配置:
{ "compilerOptions": { "target": "ES2020", "module": "CommonJS", "esModuleInterop": true, "skipLibCheck": true, "strict": true, "outDir": "./dist" }, "include": ["index.ts"] }
- 执行命令(完全符合你的需求):
tsc && node dist/index.jsnodemon -r ts-node index.ts
内容的提问来源于stack exchange,提问作者Daniele Ricci
相关产品推荐
相关产品推荐

