我有一个 ES6 模块 right.mjs
。将其作为参数执行到 node
效果很好:
$ node --version
v8.10.0
$ node --experimental-modules right.mjs
(node:4492) ExperimentalWarning: The ESM module loader is experimental.
executing right module
`executing right module` is the output of the module.
与此相反,REPL 中的以下输入等待进一步的输入:
$ node --experimental-modules
> (node:4526) ExperimentalWarning: The ESM module loader is experimental.
> import 'right.mjs';
...
我不明白为什么。
与以下相同:
> import './right.mjs';
...
尝试 require
结果:
> require('./right.mjs');
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/xxx/right.mjs
at Object.Module._extensions..mjs (module.js:686:11)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
那么,如何在 Node.js REPL 中导入 ES 模块?
原文由 Min-Soo Pipefeet 发布,翻译遵循 CC BY-SA 4.0 许可协议
目前这是不可能的。 ES 模块应该是从 ES 模块范围导入的,而 REPL 不被认为是一个。这可以随着时间的推移而改善,因为对 ES 模块的支持是实验性的。
require
和import
的使用在 Node.js 模块实现中是互斥的,REPL 已经使用了require
。自 Node.js 13 起,REPL 支持动态
import
。使用node --experimental-repl-await
,它是: