You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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版本,不需要调整项目模块规则:

  1. 先安装对应依赖:
npm install node-fetch@2
npm install @types/node-fetch@2 -D
  1. package.json 不需要添加"type": "module"字段,其余依赖和scripts可保留原有配置
  2. tsconfig.json 配置:
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "strict": true,
    "outDir": "./dist"
  },
  "include": ["index.ts"]
}
  1. 执行命令(完全符合你的需求):
  • tsc && node dist/index.js
  • nodemon -r ts-node index.ts

内容的提问来源于stack exchange,提问作者Daniele Ricci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:24:04