Dual package interoperability
A dual package offers entry points for both ES modules and CommonJS. If the two entry points create separate state, consumers can disagree about shared counters, caches or class identity. 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. Two passing separate-process tests do not establish shared module identity within one process. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/packages.html.
Formal Syntax & Structure
createRequire(import.meta.url); import(specifier)Working Example
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);