【问题标题】:Node.js - Must use import to load ES Module: [duplicate]Node.js - 必须使用导入来加载 ES 模块:[重复]
【发布时间】:2021-12-02 04:00:28
【问题描述】:

我用谷歌搜索了一段时间,但找不到解决问题的解决方案。

我想使用“node-fetch”中的 fetch 函数,但是在我的代码中需要它时,我得到了错误:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/src/index.js from /Users/xvma/stuff/Projekte/React/first-try/test.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/xvma/stuff/Projekte/React/first-try/node_modules/node-fetch/package.json.

Terminal output

In this file I want to use fetch()

My server.js

我希望你们能帮助我,我尝试删除我的节点组件文件夹和包锁,但没有奏效。 另外,在我的 package.lock.json 中没有设置“type”="module"。

【问题讨论】:

  • 请不要将您的错误和代码发布为图片!
  • 你不需要 require "node-fetch" 来使用 fetch。

标签: node.js


【解决方案1】:

看起来您正在使用node-fetch 3,它仅作为 ESM 模块分发,而不是 require()able CJS 模块。

  • 目前,您只需降级到低于版本 3 的 node-fetch
  • 或者,您可以在 ESM 上全力以赴,将脚本重命名为 server.mjs 并在任何地方使用 import

【讨论】:

  • 已经解决了,非常感谢!
猜你喜欢
  • 2020-08-23
  • 2021-07-30
  • 2021-11-02
  • 2021-12-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 2022-07-13
  • 2021-10-01
相关资源
最近更新 更多