node.js - 如何在 Node 8 的 Node.js REPL 中导入 ES 模块?

标签 node.js import module

我有一个 ES6模块 right.mjs。将它作为 node 的参数执行效果很好:

$ 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.

与此相反,REPL 中的以下输入等待进一步输入:

$ node --experimental-modules
> (node:4526) ExperimentalWarning: The ESM module loader is experimental.

> import 'right.mjs';
...

我不明白为什么。

同理:

> import './right.mjs';
...

尝试要求会导致:

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

那么,如何在 Node.js REPL 中导入 ES 模块?

最佳答案

在 Node.js v14 中是可以的,但是你需要使用 import 函数,而不是 import 语句。

$ 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"

关于node.js - 如何在 Node 8 的 Node.js REPL 中导入 ES 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784608/

相关文章:

node.js - 使用 ES6 类的快速路由

node.js 主进程被 ABRT 信号杀死,但没有被 process.on ("SIGABRT"捕获,...)

mysql - 是否可以将我的数据库导入另一台服务器?

android - 导入 R. (android)

java - 从 Informix 批量导入到 Oracle

azure - 安装 powershell 模块使 Azure Functions 无法正常工作

Javascript 字符串到正则表达式而不转义

javascript - Nodejs 从请求范围内检索正文

linux - 在 Linux 内核中使用 __exit token

linux - 无法插入某些 Linux 模块。各种错误