Using the Node.js REPL, how can you import modules using ecmascript syntax? Does any version of the Node.js REPL allow this now?
In Node.js v10.16.0, I'm accessing the REPL using this command:
node --experimental-modules
source: https://nodejs.org/api/esm.html#esm_enabling
CommonJS is ancient technology. Is Node.js still under active development? I wonder if the deno REPL can do this?
You cannot use static import
statements (e.g. import someModule from "some-module"
), at the moment, & I'm not aware of any efforts/tickets/pr's/intents to change that.
You can use import()
syntax to load modules! This returns a promise. so for example you can create a variable someModule
, start importing, & after done importing, set someModule
to that module:
let someModule
import("some-module")
.then( loaded=> someModule= loaded)
Or you can directly use the import in your promise handler:
import("some-module").then(someModule => someModule.default())
For more complex examples, you might want to use an async Immediately Invoked Function Expression, so you can use await
syntax:
(async function(){
// since we are in an async function we can use 'await' here:
let someModule = await import("some-module")
console.log(someModule.default())
})()
last, if you start Node.JS with the --experimental-repl-await
flag, you can use async directly from the repl & drop the async immediately invoked function:
let someModule = await import("some-module")
// because you have already 'await'ed
// you may immediately use someModule,
// whereas previously was not "loaded"
console.log(someModule.default())
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