تكرار السؤال: …
الإجابة المختصرة
يحدث عندما يتم استيراد نسختين مختلفتين من نفس المكتبة في نفس التطبيق مما يؤدي لتكرار الـ Singletons وكسر الـ instanceof.
الشرح
إذا استورد جزء من التطبيق نسخة CJS واستورد جزء آخر نسخة ESM، سيتم تحميل الملفين ككيانين مستقلين في الذاكرة مما يفسد الحالة المشتركة.
مثال بالكود
// package.json — expose both builds but make ESM a thin wrapper over the CJS build
// {
// "name": "my-lib",
// "exports": { ".": { "import": "./wrapper.mjs", "require": "./dist/index.cjs" } }
// }
// wrapper.mjs — ESM entry that re-exports the CommonJS build, so only ONE copy of the library exists
import cjs from "./dist/index.cjs";
export const { createClient, Client } = cjs;
export default cjs;
// Without the wrapper, an app that loads the library through both require() and import gets two copies:
// two singletons, and `instanceof Client` returns false across the boundary.أخطاء شائعة
- كتابة كود يعتمد على حالة مشتركة دون تأمين wrapper موحد للحزمة.
أسئلة متابعة
- ما هي حقول 'exports' في package.json وكيف تفوقت على حقل 'main' القديم؟
- كيف تتعامل Node.js مع مشكلة التبعيات الدائرية (Circular Dependencies) بين CJS و ESM؟