Ship ESM and CommonJS with conditional exports
Publish one package that works with import and require by mapping each condition to its own file in exports, and avoid loading both copies at once.
Some of your users run require(), and others use import. Map each condition to its own build in exports, and give each build its own types file.
{
"name": "my-lib",
"version": "1.0.0",
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
}
}With "type": "module", .js files are ESM and .cjs files are CommonJS, so no further flag is needed. Either style gets the same answer:
node -e "console.log(require('my-lib').add(1, 2))"
node --input-type=module -e "import { add } from 'my-lib'; console.log(add(1, 2))"3
3Node.js picks the import or require condition from how the consumer loaded the package, as described in conditional exports. The hazard is state: an app that loads both builds holds two copies of any singleton, so keep shared state in a third module or avoid it.