使用require引入node-fetch报ERR_REQUIRE_ESM错误该如何解决?
node-fetch引入报错解决方案
报错原因
node-fetch v3及更高版本已完全迁移为ESM-only模块,不再支持CommonJS规范的require()语法引入,因此在CommonJS项目中直接用require('node-fetch')会触发ERR_REQUIRE_ESM错误。
可选解决方案
方案1:安装支持CommonJS的v2版本(最快捷,无需修改项目配置)
v2版本的node-fetch仍然兼容CommonJS规范,适合不想改动现有项目结构的场景:
- 卸载当前安装的高版本node-fetch:
npm uninstall node-fetch
- 安装v2.x版本的node-fetch:
npm install node-fetch@2
- 原有引入语句
const fetch = require('node-fetch')无需修改,可直接正常使用。
方案2:CommonJS项目中使用动态import()引入
如果需要使用v3及以上版本的新特性,又不想把项目改为ESM规范,可以使用Node.js支持的动态import语法:
- Promise写法示例:
import('node-fetch').then(({default: fetch}) => { // 所有使用fetch的逻辑写在此作用域内 fetch('https://example.com') .then(res => res.json()) .then(data => console.log(data)) })
- async/await写法示例:
async function yourFunction() { const {default: fetch} = await import('node-fetch') const res = await fetch('https://example.com') const data = await res.json() console.log(data) } yourFunction()
方案3:将项目改为ESM规范
如果愿意调整项目整体模块规范,可以直接使用ES模块的引入语法:
- 在项目根目录的
package.json文件中新增配置项:
{ "type": "module" }
- 将原有
const fetch = require('node-fetch')替换为ES模块引入语句:
import fetch from 'node-fetch'
注意:修改为ESM规范后,项目内所有原有的CommonJS语法(如require()、module.exports等)都需要替换为对应的ESM写法。
内容的提问来源于stack exchange,提问作者Alex Stroescu
相关产品推荐
相关产品推荐

