Home >Web Front-end >JS Tutorial >My React Journey: Day 11
What I Learned Today
Modules are a game-changer in JavaScript. They allow us to break down code into smaller, reusable chunks, making it easier to manage, debug, and optimize our projects. Here’s a breakdown:
What Are Modules?
Key Concepts
Syntax:
// Export export const greet = () => console.log("Hello!"); export const add = (a, b) => a + b; // Import import { greet, add } from "./module.js"; greet(); // Output: Hello! console.log(add(2, 3)); // Output: 5
Export a single default item. You can rename it during import.
// Export export default function greet() { console.log("Hello, default export!"); } // Import import hello from "./module.js"; hello(); // Output: Hello, default export!
Key Difference:
2.Module Alias
import { sum as add } from "./math.js"; console.log(add(2, 3)); // Output: 5
3.Namespace Import (*)
import * as math from "./math.js"; console.log(math.sum(2, 3)); // Output: 5 console.log(math.sub(5, 2)); // Output: 3
4.Combine Exports
Steps:
// Module 1: calc.js export const add = (a, b) => a + b; export const sub = (a, b) => a - b; // Module 2: identity.js export const name = "JavaScript"; // Combine Modules export * as calc from "./calc.js"; export * as identity from "./identity.js"; // Import Combined import * as modules from "./combine.js"; console.log(modules.calc.add(5, 3)); // Output: 8 console.log(modules.identity.name); // Output: JavaScript
Benefits of Using Modules
Reflection
I’m enjoying learning how modules simplify and enhance JavaScript development. The combination of exports, imports, aliases, and namespaces makes managing projects much more efficient.
We keep moving—learning harder! ?
The above is the detailed content of My React Journey: Day 11. For more information, please follow other related articles on the PHP Chinese website!