📦 Node.js - מודולים (Modules)

📘 מה זה מודול?

מודול הוא קובץ JavaScript שמכיל קוד מבודד. כל משתנה או פונקציה שמוגדרים בו נשארים במרחב השמות המקומי שלו, אלא אם כן מייצאים אותם. Node.js מאפשר לבנות אפליקציה ממודולים קטנים וניתנים לשימוש חוזר.

🧰 מודולים מובנים

Node.js מגיע עם ספריית ליבה של מודולים כגון fs, http,path ועוד.

import fs from "fs"; // ES Modules
// או
const http = require("http"); // CommonJS

🔄 CommonJS – require / module.exports

זה הפורמט הוותיק והמוגדר כברירת מחדל ב‑Node.js.

// math.js
function add(a, b) {
  return a + b;
}

module.exports = { add };

// index.js
const { add } = require("./math");
console.log(add(2, 3)); // 5

✨ ES Modules – import / export

נתמך החל מ‑Node 14+ כאשר ב‑package.json יש "type": "module" או כשהסיומת היא .mjs.

// math.mjs
export const multiply = (a, b) => a * b;

// index.mjs
import { multiply } from "./math.mjs";
console.log(multiply(4, 5)); // 20

📤 ייצוא ברירת מחדל

// logger.js
export default function log(message) {
  console.log("[LOG]", message);
}

// app.js
import log from "./logger.js";
log("Hello");

📦 שדות main / exports ב‑package.json

בקובץ החבילה אפשר להגדיר איזה קובץ ייטען כברירת מחדל כשדורשים את החבילה.

{
  "name": "my-lib",
  "version": "1.0.0",
  "main": "dist/index.cjs",
  "module": "dist/index.mjs",
  "types": "dist/index.d.ts",
  "exports": {
    ".": {
      "require": "./dist/index.cjs",
      "import": "./dist/index.mjs"
    }
  }
}

🌍 מודולים מצד שלישי (npm)

מתקינים עם pnpm add / npm install ומייבאים לקוד.

pnpm add lodash
import _ from "lodash";
console.log(_.shuffle([1, 2, 3, 4]));

📝 סיכום

  • מודול = קובץ נפרד עם מרחב שמות משלו.
  • CommonJS: require / module.exports.
  • ES Modules: import / export.
  • מודולים מובנים, חבילות npm ומודולים מותאמים – כולם חיים יחד.