How to use EcmaScript Modules in Node.js ?
Using ECMAScript Modules (ES Modules or ESM) in Node.js allows you to take advantage of modern JavaScript syntax for organizing and managing your code. ECMAScript Modules provide a more structured and standardized way to work with modules compared to CommonJS, which has been traditionally used in Node.js. Here’s a comprehensive guide on how to use ECMAScript Modules in Node.js:
Node.js treats JS code as CommonJS modules by default, However, the EcmaScript modules can be used instead of using the --experimental-modules flag.
The approaches to use EcmaScript modules in Node.js are:
Table of Content
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2: Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y

Add the below syntax and The updated dependencies in package.json file will look like:
"type" : "module"

Using package.json
Configuration
Alternatively, you can configure your package.json
to use ECMAScript Modules globally by setting "type": "module"
:
Example: Implementation to show the use of EcmaScript modules in Node.js
// area.js
const areaOfRectangle = (length, breadth) => {
return length * breadth
}
export default areaOfRectangle
Node
// index.js
import areaOfRectangle from './area.js'
console.log('Area of rectangle: ', areaOfRectangle(5, 8))
Output:

Using .mjs
File Extension
Create a module file with the .mjs
extension. For example, create a file named module.mjs
:
// module.mjs
export function greet(name) {
return `Hello, ${name}!`;
}
Features of ECMAScript Modules in Node.js
- Named Exports: Export multiple variables, functions, or classes from a module using named exports.
- Default Exports: Export a single variable, function, or class as the default export.
- Importing: Import named exports or the default export from other modules.
- Asynchronous Module Loading: Use dynamic imports (
import()
syntax) for loading modules asynchronously.
Differences from CommonJS (require)
- Syntax: Use
import
andexport
keywords instead ofrequire
andmodule.exports
. - Scope: ECMAScript Modules are scoped to the file (similar to ES6 modules in the browser), while CommonJS modules are evaluated synchronously and share a global module scope.
- Static Analysis: ECMAScript Modules allow for more efficient static analysis and optimization by the JavaScript engine.
Conclusion
Using ECMAScript Modules in Node.js provides a modern and standardized approach to modular JavaScript development. By following the steps outlined above, you can start leveraging ECMAScript Modules in your Node.js applications to take advantage of improved code organization, module encapsulation, and support for modern JavaScript syntax.