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

查看:1018
本文介绍了如何在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

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的使用在节点模块实现中是互斥的,REPL已经使用require.

This is currently impossible. 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.

在REPL中期望对动态import的支持,尚不支持,最新的Node 11版本会导致错误:

The support for dynamic import is expected in REPL, it isn't supported yet, the latest Node 11 release causes an error:

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]:未指定动态导入回调.

TypeError [ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING]: A dynamic import callback was not specified.

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

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