Ship ESM and CommonJS from One Rollup Build
Configure Rollup to emit ESM and CommonJS bundles together, map them with package.json exports, and avoid the dual-package hazard.
21 Jan 2026, 09:39 UTC

The problem: one library, two import styles
You are publishing a UI component library. A downstream team consumes it with import { Button } from '@acme/ui' in a Vite application. Another team runs const { Button } = require('@acme/ui') in a Node 18 service. If you ship only an ESM file, CommonJS callers receive an object wrapped in a default property. If you ship only CommonJS, ESM callers lose static analysis and tree-shaking benefits.
Maintaining two separate build configurations doubles the chance that one format drifts behind the other. Rollup can emit both bundles from the same input in a single command, and Node's exports field routes each consumer to the correct file.
Configure one build for two outputs
Rollup accepts an array of output objects. Each object can target a different format, file path, and interop behavior. The example below assumes a TypeScript source file at src/index.ts and React as an external peer dependency.
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/index.ts',
external: ['react', 'react-dom'],
plugins: [
nodeResolve(),
typescript({ tsconfig: './tsconfig.build.json' }),
],
output: [
{
format: 'esm',
file: 'dist/index.mjs',
exports: 'named',
sourcemap: true,
},
{
format: 'cjs',
file: 'dist/index.cjs',
exports: 'named',
esModule: false,
interop: 'defaultOnly',
sourcemap: true,
},
],
};
Run this from the library root:
cd
npx rollup -c
npx downloads Rollup if it is not installed locally; prefer ./node_modules/.bin/rollup -c so the build uses your pinned version. No special permissions are required. After the command finishes, check that dist/ contains both index.mjs and index.cjs:
ls dist/
Setting esModule: false on the CJS output tells Rollup to skip the __esModule marker it normally adds. The result is a plain module.exports assignment that matches Node's native CommonJS expectations. The interop: 'defaultOnly' option limits generated helper code to default-import handling; use 'auto' if your consumers rely on named-import interop, but expect larger output.
Externalizing react and react-dom keeps them out of your bundle. Consumers install their own copies, which avoids duplicate React instances and reduces bundle size.
Map formats with package.json exports
Node 12.17+ supports the exports field, which tells Node which file to return for import versus require(). Add this to your package.json:
{
"name": "@acme/ui",
"version": "1.0.0",
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"default": "./dist/index.mjs"
}
},
"sideEffects": false,
"peerDependencies": {
"react": ">=18.0.0",
"react-dom": ">=18.0.0"
}
}
The type: "module" field makes Node treat .js files as ESM by default, so the explicit .mjs and .cjs extensions remove ambiguity. Keep main and module as fallbacks for older bundlers that do not read exports.
For subpaths such as @acme/ui/icons, add explicit entries rather than relying on wildcards:
"exports": {
".": { ... },
"./icons": {
"import": "./dist/icons.mjs",
"require": "./dist/icons.cjs"
}
}
Interop trade-offs and the dual-package hazard
Rollup's interop option controls how default and named exports are translated between formats:
| Value | Behavior | Risk |
|---|---|---|
auto | Adds __esModule checks and helper wrappers | Larger CJS output; familiar to most bundlers |
compat | Wraps ESM namespaces for CJS require | Can behave differently than native ESM in edge cases |
esModule | Always sets __esModule | May confuse plain CommonJS consumers |
defaultOnly | Handles only default imports; minimal helpers | Named imports may arrive as undefined depending on consumer tooling |
There is a deeper risk than helper code: the dual-package hazard. If a consumer imports your library with import in one file and require() in another, Node may load two separate copies. If your library holds mutable state (a singleton counter, a React context, an event emitter), each copy gets its own state. Avoid module-level mutable state, or document that consumers should pick one import style.
Verify before you publish
Build artifacts are not enough. Create a temporary consumer project outside the library and test both entry points:
- ESM consumer: Add
"type": "module"to its package.json, then runnode --input-type=module -e "import('@acme/ui').then(m => console.log(Object.keys(m)))". - CJS consumer: Run
node -e "const ui = require('@acme/ui'); console.log(Object.keys(ui))".
Expected result: both commands expose your named exports without a default wrapper, unless your source intentionally exports only a default. If the CJS result shows default as the only key, revisit exports and esModule settings.
TypeScript declarations require a separate pass. Run tsc --emitDeclarationOnly --outDir dist/types (or use @rollup/plugin-dts) and confirm the declaration paths match your exports entries so IDEs resolve the right types.
Limitations
- Watch mode rebuilds both formats on any source change. Use separate development and production configs if rebuild time becomes painful.
- The
exportsfield is ignored by Node versions older than 12.17; older consumers fall back tomain. - Tree-shaking works best on the ESM bundle. Downstream bundlers may still retain dead code in the CJS bundle even with
sideEffects: false.
Ship both formats from one command
You do not need separate repositories, separate CI jobs, or hand-maintained dual entry points. Configure Rollup's output array once, externalize peer dependencies, map the results with exports, and verify both import and require in scratch consumer projects before you tag a release.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.