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

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.


It is possible in Node v14, but you need to use the import function, rather than the import statement.

$ 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"

Not precisely what was asked about (not really REPL), but (using node 12.6.0), it is possible to execute ESM code from command line via --eval:

  1. First, if your ES modules have .js extension instead of .mjs, put "type": "module" in package.json (see https://nodejs.org/api/esm.html#esm_enabling) to allow node treating JS files as modules
  2. Run node --experimental-modules --input-type=module --eval 'code here'

You could alias this as esmeval for example:

alias esmeval='node --experimental-modules --input-type=module --eval'

And then you can use it as:

esmeval 'import { method } from "./path/to/utils.js"; console.log(method("param"))'

If you can't use node 12 yet as a primary version, but can in install via nvm, make the alias point to the v12 installation:

alias esmeval='/c/software/nvm/v12.6.0/node.exe --experimental-modules --input-type=module --eval'