JavaScript Modules

JavaScript Modules

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)

// file: math.js export const PI = 3.14159; export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }

Default Export (Single Export per File)

// file: greet.js export default function greet(name) { return `Hello, ${name}!`; }

1.2 Importing

Import Named Exports

// file: main.js import { PI, add, subtract } from "./math.js"; console.log(PI); // 3.14159 console.log(add(5, 3)); // 8 console.log(subtract(10, 4)); // 6

💡 Use {} to import multiple named exports.

Import Default Export

// file: main.js import greet from "./greet.js"; console.log(greet("Alice")); // "Hello, Alice!"

💡 No {} is used for default exports.

Import Everything (*)

// file: main.js import * as math from "./math.js"; console.log(math.PI); // 3.14159 console.log(math.add(2, 2)); // 4

💡 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.

// file: main.js async function loadMath() { const math = await import("./math.js"); console.log(math.add(3, 4)); // 7 } loadMath();

✅ 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.

<script type="module" src="main.js"></script>

📌 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.

{ "type": "module" }

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. 😃

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close