ES Modules in Node.js
Learn how to use the modern JavaScript module system in Node.js with import, export, named exports, default exports and practical examples.
1. What Are ES Modules?
ES Modules (ESM) are the standard JavaScript module system. They allow developers to divide code into separate files and share functions, variables, classes and other values between those files.
ES Modules use two main keywords:
export: Makes selected functionality available to other modules.import: Loads exported functionality into another module.
For example, we can define a multiplication function in
math.mjs and use it in app.mjs.
This avoids duplicating the same function in multiple files.
2. Why Do We Use ES Modules?
- Code Reusability: Share functions between files.
- Better Organization: Keep related functionality in separate modules.
- Easy Maintenance: Modify a feature in its own module.
- Named Imports: Import the specific values needed from a module.
- Default Exports: Export one primary value from a module.
- Standard Syntax: Use the same module syntax in modern JavaScript environments that support ESM.
3. How ES Modules Work
An ES module exports a function or value. Another module imports that value and uses it in its own code.
math.mjs
function add(a, b) { ... }
Create the reusable function.
export
export function add(a, b) { ... }
Expose the function.
app.mjs
import { add } from "./math.mjs";
Load the exported function.
Call the Function
add(10, 20)
Result: 30
4. Named Exports
A named export exports a function, variable or class using its declared name. A module can contain multiple named exports.
Step 1: Create math.mjs
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const instituteName = "CIIT Training Institute";
Step 2: Import Values in app.mjs
import { add, subtract, instituteName } from "./math.mjs";
console.log(instituteName);
console.log("Addition:", add(20, 10));
console.log("Subtraction:", subtract(20, 10));
Expected Output
CIIT Training Institute Addition: 30 Subtraction: 10
Explanation
- The
add()function is exported by name. - The
subtract()function is also exported by name. - The
instituteNameconstant is another named export. - The importing file uses curly braces to select the named exports.
- The imported functions are called like normal functions.
as keyword.
5. Import Using an Alias
An alias allows an imported value to be referred to by a different local name. It is useful when avoiding naming conflicts or choosing a more meaningful name.
import { add as calculateSum } from "./math.mjs";
console.log(calculateSum(15, 25));
Expected Output
40
Here, the exported function is named add, but it
is used locally through the name calculateSum.
6. Default Export
A default export is used when a module has one primary value or function that it wants to export as its default. A module can have only one default export.
Step 1: Create greeting.mjs
export default function greet(name) {
return "Hello, " + name + "!";
}
Step 2: Import in app.mjs
import greet from "./greeting.mjs";
console.log(greet("Student"));
Expected Output
Hello, Student!
Notice that the default import does not require curly braces. The importing file can choose its local name for the default import.
7. Named Export vs Default Export
| Feature | Named Export | Default Export |
|---|---|---|
| Syntax | export function add() { ... } |
export default function greet() { ... } |
| Imports | Usually uses curly braces. | Does not use curly braces for the default import. |
| Number per module | A module can have multiple named exports. | A module can have only one default export. |
| Import naming | Use the exported name or an alias. | The importing file chooses a local name. |
8. Import All Named Exports
We can import all named exports from a module under a single
namespace object using the * as syntax.
import * as math from "./math.mjs";
console.log(math.add(10, 5));
console.log(math.subtract(10, 5));
Expected Output
15 5
Here, math acts as a namespace object for the module's
named exports. The functions are accessed using dot notation.
9. ES Modules with Node.js
Node.js supports ES Modules. There are two common ways to identify a file as an ES module.
Method 1: Use the .mjs Extension
Files ending in .mjs are treated as ES modules.
For example, use app.mjs and math.mjs.
node app.mjs
Method 2: Configure package.json
In a Node.js project, adding "type": "module" to
package.json makes ordinary .js files
in that package scope use ES Module syntax.
{
"type": "module"
}
With this configuration, you can use app.js and
math.js with import and export.
10. Practical Example: Student Module
Let's create a module that returns student details and import it into the main application.
Step 1: Create student.mjs
export function getStudent(name, course) {
return {
name,
course
};
}
Step 2: Create app.mjs
import { getStudent } from "./student.mjs";
const student = getStudent("Samadhan", "Node.js");
console.log("Student:", student.name);
console.log("Course:", student.course);
Expected Output
Student: Samadhan Course: Node.js
The student module owns the logic for creating a student object. The main application imports and uses that functionality.
11. ES Module Execution Flow
student.mjs
export function getStudent() { ... }
Defines and exports functionality.
app.mjs
import { getStudent } from "./student.mjs";
Imports the named export.
Create Student
getStudent("Samadhan", "Node.js")
Receives a student object.
Display Details
Student: Samadhan
Course: Node.js
12. Common Mistakes
| Mistake | Correct Approach |
|---|---|
| Using curly braces for a default import. | Import a default export without curly braces. |
| Importing a named export using the wrong name. | Match the exported name or use an alias. |
| Using an incorrect file path. | Verify the relative path and file extension. |
| Forgetting to export a function. | Export the function before importing it elsewhere. |
| Running an ES module as CommonJS. | Check the file extension and package configuration. |
13. Practice Tasks
Task 1: Create a Calculator Module
Export addition and multiplication functions from
calculator.mjs. Import them into
app.mjs and display the results.
Addition: 30
Multiplication: 200
Task 2: Use a Default Export
Create a default-exported function that returns a welcome message. Import the function in another file and display it.
Expected Output:Welcome to Node.js Modules!
Task 3: Create a Student Module
Export a function that accepts a student's name and course and returns an object. Import it and display both properties.
Expected Output:Student: Pradnya
Course: JavaScript
Summary
ES Modules are the standard JavaScript module system used to organize code into reusable files. The export keyword makes functions, variables and classes available to other modules, while import allows another file to use the exported values. Named exports support sharing multiple values, and a default export provides one primary exported value from a module. Node.js supports ES Modules through the .mjs extension or suitable package configuration. These features improve code organization, reusability, readability and maintainability in Node.js applications.