What is ES Modules in Node.js: Explanation and Example
ES modules are a modern way to organize and share code using import and export statements. They allow you to split your code into reusable pieces with clear dependencies, improving readability and maintainability.How It Works
Think of ES modules like separate rooms in a house where each room has its own purpose and items. Instead of putting everything in one big room, you keep things organized by splitting them into smaller rooms. In Node.js, ES modules let you split your code into files that can share functions, objects, or values by explicitly exporting them from one file and importing them into another.
This system works by Node.js reading the import and export statements to know exactly what parts of the code are needed and where. It loads only those parts, making your program cleaner and easier to understand. Unlike older ways, ES modules use a strict syntax and run in a special mode that helps catch errors early.
Example
This example shows how to create a simple module that exports a greeting function, and how to import and use it in another file.
// greet.js export function sayHello(name) { return `Hello, ${name}!`; } // app.js import { sayHello } from './greet.js'; console.log(sayHello('Alice'));
When to Use
Use ES modules in Node.js when you want to write modern, clean, and maintainable code that clearly shows dependencies between files. They are especially useful for larger projects where organizing code into smaller parts helps teamwork and debugging.
ES modules are also the standard for JavaScript on the web, so using them in Node.js makes it easier to share code between server and browser environments. If you want to use the latest JavaScript features and tools, ES modules are the way to go.
Key Points
- ES modules use
importandexportto share code between files. - They run in strict mode, helping catch errors early.
- Node.js supports ES modules natively with the
.mjsextension or by setting"type": "module"inpackage.json. - They improve code organization and compatibility with browser JavaScript.