Skip to content
jshacks.dev
Tooling

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.

1 min read
Summarize in AI

A library should ship the formats its users load. Rollup takes one input and writes several outputs.

rollup.config.jsJavaScript
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' },
  ],
};
Shell
npx rollup -c
Text
src/index.js → dist/index.js, dist/index.cjs...
created dist/index.js, dist/index.cjs in 112ms

external 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.

Taggedrollup
Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Tooling

Configure VS Code settings for a team

Share VS Code settings and recommended extensions with a team by committing a .vscode folder with settings.json and extensions.json.

1 min read
Tooling

Share an ESLint config across packages

Share one ESLint 9 flat config across workspace packages by exporting an array from a package and spreading it into each package's eslint.config.js.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.