In a project I am collaborating on, we have two choices on which module system we can use:
require
, and exporting using module.exports
and exports.foo
.import
, and exporting using ES6 export
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?
NOTE: You must note that you can't use require and import at the same time in your node program and it is more preferred to use require instead of import as you are required to use the experimental module flag feature to run import program.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .
Cases where it is necessary to use both “require” and “import” in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you.
Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.
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 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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With