Open In App

How to use EcmaScript Modules in Node.js ?

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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
Screenshot-2024-07-02-125241

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 Node


// 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 and export keywords instead of require and module.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.



Next Article

Similar Reads