Configure Rollup for a library with multiple formats
Configure Rollup 4 to build one library into ESM and CommonJS files with an output array, and keep dependencies out of the bundle as externals.
A library should ship the formats its users load. Rollup takes one input and writes several outputs.
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
export default {
input: 'src/index.js',
external: [...Object.keys(pkg.dependencies ?? {})],
output: [
{ file: 'dist/index.js', format: 'es' },
{ file: 'dist/index.cjs', format: 'cjs', exports: 'named' },
],
};npx rollup -csrc/index.js → dist/index.js, dist/index.cjs...
created dist/index.js, dist/index.cjs in 112msexternal marks your dependencies as imports left in the output, so users get one copy from their own install and not one baked into your file. The exports: 'named' setting stops Rollup from guessing, and from warning when a module has both named and default exports. See Rollup's configuration options.
Point your package exports map at both files. The time in the output is an example. Subpath imports such as lodash/get are not covered by a plain name list, so use a function or a regular expression for external if you use them.