Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "import" in node REPL

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

enter image description here

CommonJS is ancient technology. Is Node.js still under active development? I wonder if the deno REPL can do this?

like image 233
Lonnie Best Avatar asked Jul 10 '19 05:07

Lonnie Best


1 Answers

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())
like image 157
rektide Avatar answered Nov 16 '22 16:11

rektide