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

编程入门 行业动态 更新时间:2024-10-28 14:23:10
本文介绍了如何在Node.js REPL中导入ES模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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结果:

> 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模块?

推荐答案

This is not currently possible。ES模块应该是从ES模块作用域导入的,而REPL不被认为是这样的。这可以随着时间的推移而改进,因为对ES模块的支持是实验性的。require和import的使用在Node.js模块实现中是互斥的,而REPL已经使用了require。

从Node.js 13开始,REPL支持动态import,node --experimental-repl-await为:

await import('./right.mjs');

更多推荐

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

本文发布于:2023-10-15 00:38:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   如何在   Node   js   REPL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!