Welcome to Part 13 of the JavaScript for Beginners Series. In this part, we learn about ES6 Modules, the modern standard for organizing JavaScript code.
Why Do We Need Modules?
As your applications grow, you can’t keep all your code in one giant file. Modules allow you to split your code into separate, reusable files. You can then share functions, variables, or classes between these files. This is the foundation of how modern frameworks like React organize code into components. فاش كيكبر البرنامج ديالك، مستحيل تخلي الكود كامل فملف (file) واحد. الـ Modules كيخليوك تقسم الكود ديالك على بزاف ديال الملفات لي تقدر تعاود تستعملهم. هكذا كتقدر تشارك الدوال (functions) والمتغيرات (variables) بين هاد الملفات. هاد المبدأ هو الأساس لي خدامين بيه الـ frameworks بحال React باش كينظمو الكود على شكل components.
Key Keywords:
- export (تصدير): The keyword used to make variables or functions available to other files.
- import (إستيراد): The keyword used to bring those exported variables or functions into the current file.
Types of Exports
Named Exports
You can export multiple variables or functions from a single file. When you import them, you must use the exact same name inside curly braces {}. كتقدر تصدر بزاف ديال الحوايج من ملف واحد. فاش كتبغي تجيبهم، خاصك تستعمل نفس السمية ديالهم وسط {}.
Default Export
You can only have one default export per file. It’s used for the "main" thing you want to export. When you import it, you can give it any name you want. كتقدر دير غير وحدة فكل ملف. كتستعملها للحاجة الرئيسية لي باغي تصدرها. فاش كتبغي تجيبها، كتقدر تعطيها أي سمية بغيتي.
Code Example
Here is how you organize code between two files: helpers.js and main.js.
// 📁 helpers.js (This is one file)
// Named Export
export const PI = 3.14;
// Named Export
export function add(a, b) {
return a + b;
}
// Default Export
export default function sayHello(name) {
return `Hello, ${name}`;
}// 📁 main.js (This is another file)
// Import the default export and give it a name (no braces)
import greet from './helpers.js';
// Import the named exports using their exact names (with braces)
import { PI, add } from './helpers.js';
console.log(greet("Amina")); // Output: Hello, Amina
console.log(`The value of PI is ${PI}`); // Output: The value of PI is 3.14
console.log(`2 + 3 = ${add(2, 3)}`); // Output: 2 + 3 = 5