问题描述
只是想知道我们如何在 node.js 8 中导入模块 - 我们还在使用 require
吗?
Just wonder how do we import a module in node.js 8 - are we still using require
?
或者我们是否仍然需要 babel 来使用 import
?
Or do we still need babel for using import
?
我一直在挖掘,但似乎没有答案.如果还是要使用require,那node为什么还不能实现import
?
I have been digging around but seems no answer. If we still have to use require, why can't node implement import
yet?
推荐答案
UPDATE-2018.11.15 ↓
简答
我们仍在使用 require
长答案
ESM 加载已部分登陆节点 8.5.0
,该节点于 2017 年 9 月发布.因此,它作为实验性功能已经成为规范的一部分有一段时间了:请参阅 API 文档 此处.注意事项包括需要 --experimental-modules
标志和使用新的 .mjs
扩展模块.
Long answer
ESM loading has partially landed in node 8.5.0
which was released in September 2017. As such, it has beeen part of the specs as an experimental feature for a little while: see the API documentation here. Caveats include the need for the --experimental-modules
flag and the use of a new .mjs
extension for modules.
在 ESM 加载稳定且功能齐全之前,V8 中仍然需要进行一些更改,因此与我的原始答案一样,如果您不这样做,我仍然建议坚持使用 CommonJS require
还没有将 Babel 用于其他东西
There is still changes that need to happen in V8 before ESM loading is stable and fully featured so as with my original answer, I would still advise on sticking with CommonJS require
if you don't already use Babel for other stuff
查看此帖子以获得更多教学解释
See this post for a more didactic explanation
这两种实现在幕后完全不同,所以它比眼睛看到的要多得多
The two implementations are completely different under the hood, so there is more to it than what meets the eyes
要点是规范(一直到 V8)仍然存在挥之不去的问题/疑问,因此 import
目前无法在不使用转译器的情况下在 Node 中实现
The takeaway is that there are still lingering issues/questions over the specifications (all the way to V8), and as such import
cannot currently be implemented in Node without a using a transpiler
从 贡献者:
在当前时间点,在 Node.js 甚至可以开始研究 ES6 模块的可支持实现之前,ES6 和虚拟机方面仍有许多规范和实现问题需要解决.工作正在进行中,但需要一些时间 — 我们目前至少在一年左右.
请记住,转译器只是将 ES6 模块语法转换为 CommonJS 模块语法,因此目前没有性能优势.换句话说,如果你还没有 Babel 管道,那么创建一个只是为了使用新提议的 import
语法没有太多动力,除非从积极的语法角度来看
Keep in mind that transpilers simply converts the ES6 module syntax to the CommonJS module syntax, so there is currently no performance benefits. In other words, if you don't have a Babel pipeline already, there is not much incentives to create one just to use the new proposed import
syntax, except from a proactive syntactic perspective
有关实现有何不同的更多详细信息,请参阅这篇文章
For more details on how the implementation differs, see this write up
这篇关于nodejs 8 导入模块 - 需要还是导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!