Course contentsShow
← JavaScript
Lesson 1457 of 2,72331. ModulesFree lesson

Dual Package Hazard

The problem when the same module is loaded as both CJS and ESM, creating duplicate instances.

Dual Package Hazard

What you'll learn: How loading the same module as both CommonJS and ES Module can create unexpected duplicate instances.

The Problem

The dual package hazard occurs when a single npm package can be loaded both as CommonJS (using require()) and as an ES Module (using import). When this happens, Node.js treats them as two separate modules, creating duplicate instances with separate state.

This is dangerous because you might think you're working with a singleton—one shared instance across your application—but you actually have two independent copies running simultaneously.

How It Happens

Imagine a package with both entry points:

my-package/
  index.js      (CommonJS)
  index.mjs     (ES Module)

If one file does:

const counter = require('my-package'); // CJS version

And another file does:

import counter from 'my-package'; // ESM version

You now have two separate instances of my-package in memory, each with its own state. Changes made through one won't reflect in the other.

Real-World Impact

This creates subtle bugs:

  • State isn't shared as expected
  • Singletons become duplicates
  • instanceof checks fail between versions
  • Event emitters miss events from the other version

Analogy: It's like having two separate notebooks both titled "Shopping List." You add items to one, your partner adds items to the other, and neither of you sees what the other wrote.

Key Takeaway

The dual package hazard creates duplicate module instances when the same package loads as both CommonJS and ES Module, breaking singleton patterns and shared state assumptions.