gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:38:55 28 4
gpt4 key购买 nike

我有一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com