Posted By: Anonymous
In a project I’m collaborating on, we have two choices on which module system we can use:
- Importing modules using
require, and exporting using
- Importing modules using ES6
import, and exporting using ES6
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?
Are there any performance benefits to using one over the other?
export declaration to CommonJS (
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.
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.
Since ES6 modules are part of the standard, I would use them.
Since Node v12, support for ES modules is enabled by default, but it’s still experimental at the time of writing this. 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 modules can be loaded dynamically via the
import() function. Unlike
require, this returns a promise.