使用 Node.js require 与 ES6 导入/导出 [英] Using Node.js require vs. ES6 import/export

查看:55
本文介绍了使用 Node.js require 与 ES6 导入/导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a project I'm collaborating on, we have two choices on which module system we can use:

  1. 使用require导入模块,使用module.exportsexports.foo导出.
  2. 使用 ES6 import 导入模块,使用 ES6 export 导出
  1. Importing modules using require, and exporting using module.exports and exports.foo.
  2. Importing modules using ES6 import, and exporting using ES6 export

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

Are there any performance benefits to using one over the other? Is there anything else that we should know if we were to use ES6 modules over Node ones?

推荐答案

更新

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

Update

Since Node v12 (April 2019), support for ES modules is enabled by default, and since Node v15 (October 2020) it's stable (see here). Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules.

在性能方面,新功能总是有可能不如现有功能优化得那么好.然而,由于模块文件只评估一次,性能方面可能会被忽略.无论如何,您最终都必须运行基准测试才能获得明确的答案.

Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.

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

ES modules can be loaded dynamically via the import() function. Unlike require, this returns a promise.

使用其中一种是否有任何性能优势?

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

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

Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import and export declaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.

CommonJS 和 ES6 模块之间存在技术差异,例如CommonJS 允许您动态加载模块.ES6 不允许这样做,但是有一个 API 正在开发中.

There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.

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

Since ES6 modules are part of the standard, I would use them.

这篇关于使用 Node.js require 与 ES6 导入/导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆