首页 > 解决方案 > 导入 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。

标签: node.js

解决方案


您应该使用 ES 模块导入而不是require.

import * as fetch from 'node-fetch';

如错误消息所述,您还可以使用动态导入。

const fetch = import('node-fetch');

推荐阅读