node.js - 导入 ES 模块
问题描述
我正在尝试创建一个独立的 node.js 项目。我遵循的步骤是 -
- 创建了一个新目录并用
npm init
. - 为
node-fetch
. - 尝试使用
const fetch = require("node-fetch");
语句导入 fetch 模块。
收到以下错误 -
const fetch = require("node-fetch");
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js from /Users/jatin/Desktop/test-app/index.js not supported. Instead change the require of /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js in /Users/jatin/Desktop/test-app/index.js to a dynamic import() which is available in all CommonJS modules. at Object.<anonymous> (/Users/jatin/Desktop/test-app/index.js:2:15) { code: 'ERR_REQUIRE_ESM' }
我机器上的节点版本是-v16.9.0。
解决方案
您应该使用 ES 模块导入而不是require
.
import * as fetch from 'node-fetch';
如错误消息所述,您还可以使用动态导入。
const fetch = import('node-fetch');
推荐阅读
- function - 为什么我的 CS50 过滤器边缘代码不适用于 check50?
- azure - 为什么在 Cosmos SQL API 查询的 WHERE 子句中包含分区键会增加某些查询的消耗 RU?
- .htaccess - 使用 htaccess 从 URL 中删除一个孩子
- python - 计算一个numpy矩阵有多少列包含所有正值
- excel - excel中的多个非连续行基于单元格值
- html - 如何在 html 页面中展示 html 代码?
- javascript - 如何将文本输入绑定到同一 html 页面上的另一个 div
- docker - Realmlist - IP 有效,但域无效
- regex - 在 MS Word 正则表达式中捕获组
- java - Java无法访问包外资源