JavaScript modules are like neatly packed lunchboxes—they help organize code and prevent global variable chaos! With ES6, JavaScript introduced import
and export
to make modular programming easier. Say goodbye to messy scripts and hello to organized, reusable code!
1. What Are ES6 Modules?
Modules allow you to break your code into separate files, making it easier to maintain and reuse. Before ES6, people used workarounds like immediately invoked function expressions (IIFEs) or the CommonJS module system (used in Node.js).
2. Exporting Modules
Think of exporting as putting things in a gift box and labeling it for others to use.
Named Export:
// mathUtils.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Default Export:
// greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
3. Importing Modules
When you import something, it's like unboxing a package and using what's inside.
Import Named Exports:
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // Output: 8
Import Default Export:
import greet from './greet.js';
console.log(greet('Alice')); // Output: Hello, Alice!
4. Combining Named and Default Exports
// utils.js
export const multiply = (a, b) => a * b;
export default function divide(a, b) { return a / b; }
Importing Them Together:
import divide, { multiply } from './utils.js';
console.log(divide(10, 2)); // Output: 5
console.log(multiply(10, 2)); // Output: 20
5. Dynamic Imports (Lazy Loading)
Need to import only when necessary? Use import()
!
if (someCondition) {
import('./heavyModule.js').then(module => {
module.doSomething();
});
}
6. Why Use ES6 Modules?
- Better code organization
- Reusability across multiple files
- Avoid global namespace pollution
- Lazy loading for better performance
Conclusion
ES6 modules make JavaScript cleaner and more efficient. By using import
and export
, you can build scalable applications with ease.
0 Comments