How to use "import" in node REPL
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())