Search code examples
node.jsimportmodule

How can I import an ES module in the Node.js REPL in Node 8?


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 can I import an ES module in the Node.js REPL?


Solution

  • This is not currently possible. ES modules are supposed to be imported from the 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 the Node.js module implementation, and REPL already uses require.

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

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