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?
You can type ". load " (note the space) into the REPL and drag/drop the file into the Terminal from the Finder to add the correct path to your command.
To be able to load an ES module, we need to set “type”: “module” in this file or, as an alternative, we can use the . mjs file extension as against the usual . js file extension. Also, from Node version 12.7.
It is possible in Node.js 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With