How to import an ES module in Node.js REPL?

2019-07-10 02:11发布

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 is the output of the module.

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';
... 

I don't understand why.

The same with:

> import './right.mjs';
... 

Trying to require results in:

> 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)

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

1条回答
Ridiculous、
2楼-- · 2019-07-10 02:23

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.

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]: A dynamic import callback was not specified.

查看更多
登录 后发表回答