如何在 Node.js REPL 中导入 ES 模块? [英] How to import an ES module in Node.js REPL?

查看:36
本文介绍了如何在 Node.js REPL 中导入 ES 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ES6 模块 right.mjs.将它作为 node 的参数执行效果很好:

I have an ES6 module right.mjs. Executing it as a parameter to node works well:

$ node --version
v8.10.0
$ node --experimental-modules right.mjs
(node:4492) ExperimentalWarning: The ESM module loader is experimental.
executing right module

执行正确的模块是模块的输出.

与此相反,REPL 中的以下输入等待进一步输入:

In contrast to that, the following input in the REPL waits for further input:

$ 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 模块?

So, how to import an ES module in Node.js REPL?

推荐答案

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

This is not currently possible. ES modules are supposed to be imported from ES module scope, while REPL isn't considered one. This can improve with time because the support of ES modules is experimental. The use of require and import is mutually exclusive in Node module implementation, REPL already uses require.

动态 import 从 Node 13 开始在 REPL 中被支持.使用 node --experimental-repl-await,它是:

Dynamic import is supported in REPL since Node 13. With node --experimental-repl-await, it is:

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

这篇关于如何在 Node.js REPL 中导入 ES 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆