JavaScript Modules (ES6 Modules)
JavaScript modules allow you to split code into smaller, reusable files and import them where needed. This helps organize code and improve maintainability.
1️⃣ Exporting and Importing Modules
To use modules, save files with a .js
extension and use the export
and import
keywords.
1.1 Exporting
You can export functions, variables, or classes from a module.
Named Exports (Multiple Exports)
Default Export (Single Export per File)
1.2 Importing
Import Named Exports
💡 Use {}
to import multiple named exports.
Import Default Export
💡 No {}
is used for default exports.
Import Everything (*
)
💡 math
is an object containing all exported values.
2️⃣ Dynamic Imports (Lazy Loading)
Instead of loading modules initially, you can dynamically import them when needed.
✅ Useful for performance optimization (only loads when needed).
3️⃣ Module Features
✔ Each module has its own scope (no global variables).
✔ **Modules are always in "strict mode" by default.
✔ Modules are loaded once (cached).
✔ Can be used in browsers and Node.js.
4️⃣ Using Modules in Browsers
Use the type="module"
attribute in HTML.
📌 Modules run in strict mode by default.
5️⃣ Using Modules in Node.js
Node.js supports ES Modules (.mjs
) or enable "type": "module"
in package.json
.
Conclusion
- Use
export
to make functions/variables available to other files. - Use
import
to bring in functions/variables from other modules. - Supports default and named exports.
- Dynamic imports help optimize performance.
- Works in browsers and Node.js.
🚀 Modules help write clean, reusable, and maintainable code! Let me know if you need more details. 😃