Node.js — ES Modules
CommonJS
// math.js
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
module.exports = { add, subtract };
// app.js
const math = require('./math');
console.log(math.add(2, 3));
ES Modules
// math.mjs
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
// app.mjs
import { add, subtract } from './math.mjs';
console.log(add(2, 3));
package.json for ES Modules
{
"type": "module"
}
Built-in Modules
| Module | Description |
|---|---|
| fs | File system |
| path | File paths |
| http | HTTP server |
| https | HTTPS server |
| url | URL parsing |
| os | Operating system |
| events | Event emitter |
| stream | Streams |
const fs = require('fs');
const path = require('path');
const http = require('http');
Export Patterns
// Single export
module.exports = function() {};
// Multiple exports
module.exports = {
func1: function() {},
func2: function() {}
};
// Export class
module.exports = class MyClass {};
Mini Practice
- Create a module with CommonJS
- Create a module with ES Modules
- Use built-in modules
- Export functions and classes
Up Next
Continue with NPM — package management.
Related Topics
Frequently Asked Questions about ES Modules
What is ES Modules in Node.js?
ES Modules is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn ES Modules?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ES Modules.
Why is ES Modules important in Node.js?
ES Modules is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.