如何在 Node 8 的 Node.js REPL 中导入 ES 模块?

新手上路,请多包涵

我有一个 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 许可协议

阅读 872
2 个回答

目前这是不可能的。 ES 模块应该是从 ES 模块范围导入的,而 REPL 不被认为是一个。这可以随着时间的推移而改善,因为对 ES 模块的支持是实验性的。 requireimport 的使用在 Node.js 模块实现中是互斥的,REPL 已经使用了 require

自 Node.js 13 起,REPL 支持动态 import 。使用 node --experimental-repl-await ,它是:

 await import('./right.mjs');

原文由 Estus Flask 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 Node.js v14 中是可能的,但您需要使用 import 函数,而不是 import 语句。

 $ node

Welcome to Node.js v14.4.0.
Type ".help" for more information.
> let myModule;
undefined
> import("./my-module.js").then(module => { myModule = module });
Promise { <pending> }
> myModule.foo();
"bar"

原文由 diachedelic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题