يدعم Node نظامي وحدات: CommonJS (CJS) — النظام الأصلي، باستخدام require/module.exports — و ES Modules (ESM) — المعيار، باستخدام import/. تختلف في الصيغة، وسلوك التحميل، والتوافقية.
يدعم Node نظامي وحدات: CommonJS (CJS) — النظام الأصلي، باستخدام require/module.exports — و ES Modules (ESM) — المعيار، باستخدام import/. تختلف في الصيغة، وسلوك التحميل، والتوافقية.
export// math.js
function add(a, b) { return a + b; }
module.exports = { add };
// app.js
const { add } = require("./math"); // synchronous, runtime
// math.mjs (or .js with "type": "module")
export function add(a, b) { return a + b; }
export default something;
// app.mjs
import { add } from "./math.mjs"; // static, hoisted
CommonJS ES Modules
Syntax require/module.exports import/export
Loading synchronous, runtime static, hoisted
Top-level await no yes
Tree-shaking hard yes (statically analyzable)
File extension .cjs / .js (default) .mjs / .js with "type":"module"
__dirname/__filename available not available (use import.meta.url)
// package.json
{ "type": "module" } // now .js files are treated as ESM
أو استخدم امتداد .mjs بشكل صريح. بدون هذا، يستخدم Node افتراضياً .js كـ CommonJS.
// ESM can import CommonJS:
import pkg from "some-cjs-lib"; // works (default import)
// CommonJS CANNOT require() a pure-ESM package (it's async):
const esm = require("esm-only-pkg"); // ❌ ERR_REQUIRE_ESM
// must use dynamic import: const esm = await import("esm-only-pkg");
المشكلة الرئيسية: لا يمكن لـ CJS أن تستخدم require() مع حزم ESM فقط — وهي مشكلة شائعة في الترحيل. لاحظ أيضاً أن ESM تفتقد __dirname (استخدم import.meta.url).
معرفة النظامين ضرورية للعمل الحقيقي مع Node: ESM هي المستقبل (معيار، قابلة لـ tree-shaking، top-level await، محاذاة المتصفح) والخيار الصحيح للمشاريع الجديدة، لكن جزء كبير من نظام npm والأكواد الموجودة هي CommonJS.
فهم الفروقات في الصيغة، وكيفية تفعيل ESM ("type": "module"), والقيود على التوافقية (خاصة عدم قدرة CJS على استيراد ESM) يمنع الالتباس والأخطاء الشائعة التي تنشأ عند خلط النظامين.