ES Modules in Node.js
๐ Covered in this chapter:
import/export ยท Named vs Default Exports ยท type: module ยท .mjs Files ยท Dynamic Imports
Use the modern import/export syntax in Node.js by enabling ES Modules, and understand how it differs from CommonJS.
1ES Modules in Node.js โ What You'll Learn
Use the modern import/export syntax in Node.js by enabling ES Modules, and understand how it differs from CommonJS.
Here's everything this chapter covers, in the order you'll learn it:
- What ES Modules are
- import statement
- export statement
- Named exports vs default exports
- Enabling ES Modules with "type": "module" in package.json
- .mjs file extension as an alternative
- Module paths must include file extensions
- Dynamic imports with import()
- CommonJS vs ES Modules โ key differences
2Working Example
๐ป Example: ES Modules in Node.js
JSON
โถ Run in Compiler
{
"type": "module"
}
๐ป Continued Example
JavaScript
โถ Run in Compiler
// math.js
export function add(first, second) {
return first + second;
}
// app.js
import { add } from "./math.js";
console.log(add(10, 20));
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Once "type": "module" is set, every .js file in the project is treated as an ES Module โ you can't mix require() into it directly.
- Always include the .js extension in ES Module import paths; Node.js will not resolve it automatically like bundlers do.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about es modules in node.js?
Focus on: import/export ยท Named vs Default Exports ยท type: module ยท .mjs Files ยท Dynamic Imports. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for es modules in node.js?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.