Node.js require vs. ES6 import/export
Problem
There are two module system you can choose in Node.js:
- Importing modules using
require
, and exporting usingmodule.exports
and exports.foo - Importing modules using ES6
import
, and exporting using ES6export
.
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?
Answer
At the time of writing this, there is no JavaScript engine yet that natively supports ES6 modules. If you are using Babel, Babel actually 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.
require()
from NodeJS (CommonJS)
- You can have dynamic loading where the loaded module name isn't predefined /static, or where you conditionally load a module only if it's "truly required" (depending on certain code flow).
- Loading is synchronous. That means if you have multiple requires, they are loaded and processed one by one.
import
from ES6
- You can use named imports to selectively load only the pieces you need. That can save memory.
- Import can be asynchronous (and in current ES6 Module Loader, it in fact is) and can perform a little better.
In addiion, the require
isn't standard based. It's is highly unlikely to become standard now that ES6 modules exist. In the future there will be native support for ES6 Modules in various implementations which will be advantageous in terms of performance.
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync