我正在尝试myArr从hello.js导入index.js。但是我得到一个错误
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
你好.js
export let myArr = ['hello', 'hi', 'hey'];
索引.js
import { myArr } from './hello.js';
console.log(myArr);
我哪里错了?
我正在尝试myArr从hello.js导入index.js。但是我得到一个错误
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
你好.js
export let myArr = ['hello', 'hi', 'hey'];
索引.js
import { myArr } from './hello.js';
console.log(myArr);
我哪里错了?
我运行你的代码没有问题。检查两件事:
使用版本 2。
npm install node-fetch@2
v3 中的 node-fetch 是一个仅限 ESM 的module - 您无法使用 require() 导入它。
如果您无法切换到 ESM,请使用与 CommonJS 保持兼容的 v2。将继续为 v2 发布关键错误修复。
希望这可以帮助:
我在构建 React 项目时遇到了类似的问题。
这是错误:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/pradeep/Work/my_project/node_modules/@babel/runtime/helpers/interopRequireWildcard/_index.mjs
然后我意识到我使用的节点版本与用于在此项目中安装软件包的节点版本不同。
我有两个选择:
我选择了第一种方法,它对我有用。
我不想发布关于相同的另一个问题,所以我在这里发布了一个答案。
如果您的节点版本低于 14,例如 v12 - 您必须指定标志:
node --experimental-modules your.mjs
问题是 node 目前还不支持本地导入和导出。根据文档,它仍然是实验性的。我建议您使用 babel 来编译您的代码并允许您使用导入和导出。
例如,您可以安装@babel/node包并使用以下命令运行您的项目:
npx babel-node index.js
这是@babel/node的文档。与文档状态一样,此命令仅适用于本地开发。在生产中,他们建议像配置此。快乐编码!