导入ES模块



我正在尝试创建一个独立的node.js项目。我遵循的步骤是-

  1. 创建新目录并使用npm init初始化。
  2. 安装node-fetch的新模块。
  3. 试图使用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');

最新更新