How-To Guide

How to Bundle a Library with Rollup

Build a publishable library with Rollup: multiple output formats, external peer deps, type declarations and preserving tree shaking.

On this page

  1. Introduction
  2. Library Versus Application Bundling
  3. External and Peer Dependencies
  4. Multiple Output Formats
  5. The Rollup Configuration
  6. Type Declarations
  7. Preserving Tree Shaking
  8. Common Pitfalls and Conclusion

Introduction

A library bundle has different requirements from an application bundle. It must expose clean entry points, keep its peer dependencies external so consumers do not get two copies, emit type declarations, and preserve the module structure so downstream bundlers can tree-shake unused code. Rollup is built for this: it produces flat, readable output for libraries and treats ES modules as first-class. This tutorial builds a library that publishes correctly for both ESM and CommonJS consumers.

Library Versus Application Bundling

An application bundle is the final artifact the runtime executes, so it can be aggressive: inline everything, minify, split into chunks. A library bundle is consumed by another build, so it must preserve information: keep dependencies external, keep types, and keep enough module structure for the consumer’s bundler to tree-shake.

The failure mode of treating a library like an application is a bundle with the dependency inlined, which duplicates it in every consumer that also depends on it, and a bundle with types stripped, which breaks TypeScript consumers. A library’s bundle is an interface, not a final artifact.

Versioning compounds this. A library publishes versions that consumers pin, so a bad bundle or a missing type is not a local bug but a bug for everyone who upgrades. The build must be verified against how consumers actually resolve it, which is why checking the packed tarball matters more for a library than for an application.

The consuming build also decides what it can tree-shake based on what the library declares, so the library’s packaging decisions propagate into every consumer. That is the reason the configuration here is about declaring interfaces correctly rather than producing the smallest possible file.

# library vs application bundle
application: final artifact -> inline, minify, code-split
library:     consumed by another build ->
  [ ] deps external (no duplicated copies)
  [ ] type declarations emitted
  [ ] module structure preserved for tree shaking
  [ ] multiple formats for different consumers

External and Peer Dependencies

A library must not bundle its dependencies, especially peer dependencies such as React that the consumer also has. Mark them external so they remain imports resolved by the consumer, and declare peerDependencies (and often devDependencies for local testing) so the contract is explicit. Bundling React into a component library ships two Reacts and breaks hooks.

Read the externals from package.json so the list cannot drift: everything in dependencies and peerDependencies is external, and only truly bundled internals are not. This keeps the bundle aligned with the declared contract.

import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('package.json', 'utf8'));

const external = [
  ...Object.keys(pkg.dependencies ?? {}),
  ...Object.keys(pkg.peerDependencies ?? {}),
];
// never bundle a peer dep like react: the consumer must provide one copy

Multiple Output Formats

Modern consumers use ES modules, but older tooling and some Node setups still need CommonJS. Emit both, with the package.json exports map telling consumers which file to load for which condition. A types entry points TypeScript at the declarations.

The exports map is what makes dual publishing coherent: main for CommonJS, module for ESM, types for declarations, and conditional exports for import/require. Without it, consumers guess, and a wrong guess produces a bundling or runtime error.

{
  "name": "@myorg/utils",
  "type": "module",
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  },
  "files": ["dist"]
}

The Rollup Configuration

Rollup takes the entry, marks externals, and produces the requested formats. Use preserveModules or preserve entry signatures when you want the output to stay tree-shakeable rather than collapsing into a single file, and let the consumer’s bundler do the final tree shaking.

For a small library, a single ESM file is fine; for a larger one with many exports, preserving the module structure helps consumers include only what they import. The choice is between a tidy single file and maximum tree-shakeability, and it depends on how the library is used.

import { defineConfig } from 'rollup';
import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';

export default defineConfig({
  input: 'src/index.ts',
  external: [/^react/, /^react-dom/, /^@myorg\//],
  output: [
    { file: 'dist/index.js',  format: 'es',  sourcemap: true },
    { file: 'dist/index.cjs', format: 'cjs', sourcemap: true, exports: 'named' },
  ],
  plugins: [nodeResolve(), typescript({ declaration: true, declarationDir: 'dist' })],
});

Type Declarations

TypeScript consumers need .d.ts files, emitted from the source and referenced by the package’s types entry. Generating declarations is separate from bundling: either a plugin emits them alongside, or a separate tsc step runs. Forgetting declarations makes a library unusable in a TypeScript consumer, which is most consumers.

The declarations must match the published API exactly, so generate them from the same build, not a stale copy. For a dual-format package, one types entry can serve both, as long as the API is the same across formats.

# Emit declarations in the build (plugin) or as a separate step:
tsc --emitDeclarationOnly --declaration --outDir dist
# verify the published package resolves types for a consumer:
npm pack && npx arethetypeswrong --pack .
# the "types" / "exports.types" entries must point at the emitted .d.ts

Preserving Tree Shaking

Tree shaking removes unused exports, but it only works if the bundle preserves ES module structure and marks side effects correctly. Set “sideEffects”: false in package.json only if the library truly has no import-time side effects; otherwise list the files that do, so consumers do not lose a needed side effect.

Do not transform ES modules into a format the consumer bundler cannot tree-shake, and do not add top-level side effects in modules meant to be pure. A library that advertises tree shaking and then has import-time side effects causes bugs when the consumer’s bundler drops the import.

{
  "sideEffects": false
  // OR, if some files have import-time side effects:
  // "sideEffects": ["*.css", "./src/polyfills.js"]
}
// false is only safe if NO module has import-time side effects
// declaring false wrongly => consumers drop a side effect => subtle bug

Common Pitfalls and Conclusion

Do not bundle peer dependencies; keep them external. Do not forget to emit type declarations. Do not set sideEffects false unless the library is truly side-effect free. Do not collapse the output so aggressively that tree shaking is lost. And do not publish without an exports map, leaving consumers to guess the entry.

Rollup bundles a library as an interface: dependencies and peers external, ESM and CommonJS outputs declared in an exports map, type declarations emitted, and module structure preserved for tree shaking. Configure it once, verify with a pack-and-inspect step, and consumers get a library that integrates without duplicate copies or missing types.

Sources: Rollup: Configuration options, Node.js: Packages and exports, arethetypeswrong.

FAQ

Should a library bundle its dependencies?
No. Keep dependencies and especially peer dependencies external so the consumer provides one copy. Bundling a peer like React ships two copies and breaks hooks; the bundle should contain only the library's own code.
Why emit both ESM and CommonJS?
Because consumers differ: modern tooling uses ES modules, older Node setups need CommonJS. An exports map tells each consumer which file to load, with a types entry for TypeScript, so the dual publish is coherent rather than a guess.

Related Examples