javascript - 使用 Node.js 需要与 ES6 导入/导出

标签 javascript node.js ecmascript-6 babeljs

在我正在合作的一个项目中,我们可以使用两种模块系统:

  1. 使用 require 导入模块,使用 module.exportsexports.foo 导出。
  2. 使用 ES6 import 导入模块,使用 ES6 export
  3. 导出

使用其中一种是否有任何性能优势?如果我们要使用 ES6 模块而不是 Node 模块,还有什么我们应该知道的吗?

最佳答案

更新

自 Node v12(2019 年 4 月)起,默认启用对 ES 模块的支持,自 Node v15(2020 年 10 月)起,它是稳定的(参见 here)。包含 Node 模块的文件必须以 .mjs 结尾,或者最近的 package.json 文件必须包含 "type": "module"Node documentation有更多信息,还有关于 CommonJS 和 ES 模块之间的互操作。

在性能方面,新功能总有可能不如现有功能优化得好。但是,由于模块文件只评估一次,性能方面可能会被忽略。最后,你必须运行基准测试才能得到明确的答案。

ES 模块可以通过 import() 函数动态加载。与 require 不同,这会返回一个 promise。


上一个答案

Are there any performance benefits to using one over the other?

请记住,目前还没有原生支持 ES6 模块的 JavaScript 引擎。你自己说你正在使用 Babel。 Babel 无论如何都会默认将 importexport 声明转换为 CommonJS (require/module.exports)。因此,即使您使用 ES6 模块语法,如果您在 Node 中运行代码,您将在后台使用 CommonJS。

CommonJS 和 ES6 模块之间存在技术差异,例如CommonJS 允许您动态加载模块。 ES6 不允许这样做,but there is an API in development for that .

由于 ES6 模块是标准的一部分,我会使用它们。

关于javascript - 使用 Node.js 需要与 ES6 导入/导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31354559/

相关文章:

javascript - 如何模拟异步函数的返回值?

javascript - 如何在JavaScript中获取数组中对象的所有键

javascript - 将另一个文件中的 JS 对象提取到变量中

javascript - javascript1.7 赋值中左侧无效

javascript - 制作下一个和上一个按钮,以显示敌人的名字和马力,但隐藏伤害

javascript - Angular 多次运行 Controller

node.js - 微软机器人框架: How to send raw JSON message to channels?

javascript - 我正在获取/bin/sh : [npm: not found error while executing the react image in Docker

javascript - 如何在一些代码后导入ES6(SystemJS)?

javascript - 如何取消选中多个选定的选择器中的选项