如何在节点 REPL 中使用 "import"

How to use "import" in node REPL

现在使用 Node.js REPL, how can you import modules using ecmascript syntax? Does any version of the Node.js REPL 允许吗?

在 Node.js v10.16.0 中,我正在使用以下命令访问 REPL:

node --experimental-modules

来源:https://nodejs.org/api/esm.html#esm_enabling

CommonJS 是一项古老的技术。 Node.js 是否仍在积极开发中?我想知道 deno REPL 是否可以做到这一点?

考虑到导入语句的静态性质以及引擎需要知道所有静态导入(在处理任何 non-import 相关代码之前)。您可以看到 import 语句实际上与交互式 REPL 支持不兼容。

例如,文件的中间或末尾允许导入语句,但它们会在 "non-static-import related code" 之前被提升和处理。

如果您在 REPL 会话结束时键入静态导入语句,REPL 应该做什么?

鉴于这一潜在的根本性变化,它无法轻易返回并重新运行您之前的所有命令!

直到阅读 this. Thanks Kevin Qian who also has ideas 我才想到这一点。

您目前不能使用静态 import 语句(例如 import someModule from "some-module"),而且我不知道有任何 efforts/tickets/pr's/intents 可以改变它.

您可以使用import()语法加载模块!这 returns 一个承诺。例如,您可以创建一个变量 someModule,开始导入,并在完成导入后,将 someModule 设置为该模块:

let someModule
import("some-module")
  .then( loaded=> someModule= loaded)

或者您可以直接在您的承诺处理程序中使用导入:

import("some-module").then(someModule => someModule.default())

对于更复杂的示例,您可能希望使用异步立即调用函数表达式,因此您可以使用 await 语法:

(async function(){
    // since we are in an async function we can use 'await' here:
    let someModule = await import("some-module")
    console.log(someModule.default())
})()

最后,如果您使用 --experimental-repl-await 标志启动 Node.JS,您可以直接从 repl 使用异步并删除异步立即调用的函数:

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())