如何在CommonJS项目中require ES6模块?Node v14.16.0场景
解决方案
不需要升级整个应用,有几种简便方法可以在你的CommonJS项目中使用最新版node-fetch:
方法一:使用node-fetch v2.x版本
node-fetch从v3开始转为ES模块,但v2.x版本仍保持CommonJS格式,完全兼容Node.js 14.16.0,直接用require导入即可:
const fetch = require('node-fetch'); // 使用示例 fetch('https://api.example.com') .then(res => res.json()) .then(data => console.log(data));
安装命令:npm install node-fetch@2
方法二:在CommonJS中使用动态import()
Node.js 14.16.0支持动态import()语法,你可以在异步函数中异步导入ES模块版本的node-fetch:
async function useFetch() { // 导入ES模块 const fetchModule = await import('node-fetch'); // ES模块的默认导出需要通过.default获取 const fetch = fetchModule.default; // 调用fetch const response = await fetch('https://api.example.com'); const data = await response.json(); console.log(data); } // 执行异步函数 useFetch();
这种方法不需要修改项目的模块系统,只需要在使用fetch的地方用异步方式导入即可。
方法三:局部切换模块类型(可选)
如果只想让单个文件使用ES模块,可以将该文件的后缀改为.mjs,然后在文件中使用import语句:
// fetch-utils.mjs import fetch from 'node-fetch'; export async function fetchData(url) { const res = await fetch(url); return res.json(); }
之后在CommonJS文件中通过动态import导入这个.mjs文件即可。
内容的提问来源于stack exchange,提问作者John Doherty
相关产品推荐
相关产品推荐

