Dual package interoperability
Prerequisite: node-package-exports-and-imports. Objective: Compare module identity. Tested locally on Node.js 22.16.0 Linux. Each example is independent. Use a fresh disposable working directory, save as main.mjs, then run node main.mjs. The harness uses a five-second timeout and synthetic environment. These are static code blocks, not ByteMind interactive execution.
How it works
Use explicit import and require conditions when needed. A single CommonJS implementation plus a thin ESM wrapper is one way to share state. CommonJS exports are objects; the ESM wrapper can export that same object rather than copying its properties into independent state. ESM named binding behavior and synthetic CommonJS named exports are not interchangeable. Test mixed consumers in the same process, not merely separate CLI runs. Node 22.16 also supports requiring certain synchronous ESM graphs; top-level await prevents synchronous require. Do not assume compatibility across older Node versions.
Show two independent module states
import {writeFileSync} from 'node:fs';import {createRequire} from 'node:module';writeFileSync('package.json',JSON.stringify({name:'bm-dual',exports:{import:'./esm.mjs',require:'./cjs.cjs'}}));writeFileSync('esm.mjs','export default {count:0};');writeFileSync('cjs.cjs','module.exports={count:0};');const require=createRequire(import.meta.url), c=require('bm-dual'), e=(await import('bm-dual')).default;c.count++;console.log(c.count,e.count,c===e);Expected output:
1 0 falseSeparate implementations create separate objects.
Share one implementation through an ESM wrapper
import {writeFileSync} from 'node:fs';import {createRequire} from 'node:module';writeFileSync('package.json',JSON.stringify({name:'bm-dual',exports:{import:'./esm.mjs',require:'./cjs.cjs'}}));writeFileSync('cjs.cjs','module.exports={count:0};');writeFileSync('esm.mjs',"import state from './cjs.cjs'; export default state;");const c=createRequire(import.meta.url)('bm-dual'),e=(await import('bm-dual')).default;c.count++;console.log(c.count,e.count,c===e);Expected output:
1 1 trueBoth consumer modes refer to the same exported object in this fixture.
Common mistakes
Two passing separate-process tests do not establish shared module identity within one process.
Practice
Replace the counter with a class constructor and compare identity in both package designs.
Reference candidate: node-dual-package-interoperability-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/packages.html (opened).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dual package interoperability — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Why might a dual package have two caches?
What does the wrapper fixture demonstrate?
Which test is essential for mixed-mode state?