Rollup: Library Builds (ESM + CJS)
Rollup was built around ES modules from day one, and it produces the cleanest output of the three bundlers: flat, readable, scope-hoisted code with almost no runtime. That makes it the traditional choice for libraries, where the output is read by other people's bundlers rather than by browsers, and where you usually need several formats from one source. (Vite 5–7 built with Rollup; Vite 8 uses Rolldown, a Rust bundler with the same API, so this lesson's concepts carry straight over.)
The config file
Rollup reads rollup.config.js (or .mjs/.ts) with rollup -c. A config exports one object, or an array of them:
// rollup.config.js
export default {
input: 'src/index.js',
external: ['ms'], // dependencies stay imports, not inlined
output: [
{ file: 'dist/index.js', format: 'es', sourcemap: true },
{ file: 'dist/index.cjs', format: 'cjs', sourcemap: true, exports: 'named' },
],
};| Output option | Meaning |
|---|---|
format |
es (ESM), cjs, iife, umd, amd, system |
file / dir |
one output file, or a directory (needed for code splitting / preserveModules) |
exports |
named, default, auto: how a CJS output exposes the exports |
name |
the global variable for iife/umd |
banner, footer |
text added to each file (licence headers) |
sourcemap |
true, 'inline', 'hidden' |
preserveModules |
one output file per input module instead of one bundle |
A dual-format library
mkdir -p units/src && cd units
cat > package.json <<'JSON'
{
"name": "@learner/units",
"version": "1.0.0",
"type": "module",
"exports": {
".": { "import": "./dist/index.js", "require": "./dist/index.cjs" }
},
"main": "./dist/index.cjs",
"files": ["dist"],
"dependencies": { "ms": "^2.1.3" },
"scripts": { "build": "rollup -c" }
}
JSON
npm install > /dev/null && npm install -D rollup@4.65.0 > /dev/null 2>&1
cat > src/bytes.js <<'JS'
const UNITS = ['B', 'KB', 'MB', 'GB'];
export function bytes(n) {
let i = 0;
while (n >= 1024 && i < UNITS.length - 1) { n /= 1024; i++; }
return `${Number.isInteger(n) ? n : n.toFixed(1)} ${UNITS[i]}`;
}
export const KB = 1024;
JS
cat > src/index.js <<'JS'
import ms from 'ms';
export { bytes, KB } from './bytes.js';
export const duration = (n) => ms(n, { long: true });
JS
cat > rollup.config.js <<'JS'
export default {
input: 'src/index.js',
external: ['ms'],
output: [
{ file: 'dist/index.js', format: 'es' },
{ file: 'dist/index.cjs', format: 'cjs', exports: 'named' },
],
};
JS
npm run build
ls -l dist | awk 'NR > 1 { print $5, $9 }'
echo "=== dist/index.js"; cat dist/index.js
echo "=== dist/index.cjs"; cat dist/index.cjs
> @learner/units@1.0.0 build
> rollup -c
src/index.js → dist/index.js, dist/index.cjs...
created dist/index.js, dist/index.cjs in 29ms
379 index.cjs
324 index.js
=== dist/index.js
import ms from 'ms';
const UNITS = ['B', 'KB', 'MB', 'GB'];
function bytes(n) {
let i = 0;
while (n >= 1024 && i < UNITS.length - 1) { n /= 1024; i++; }
return `${Number.isInteger(n) ? n : n.toFixed(1)} ${UNITS[i]}`;
}
const KB = 1024;
const duration = (n) => ms(n, { long: true });
export { KB, bytes, duration };
=== dist/index.cjs
'use strict';
var ms = require('ms');
const UNITS = ['B', 'KB', 'MB', 'GB'];
function bytes(n) {
let i = 0;
while (n >= 1024 && i < UNITS.length - 1) { n /= 1024; i++; }
return `${Number.isInteger(n) ? n : n.toFixed(1)} ${UNITS[i]}`;
}
const KB = 1024;
const duration = (n) => ms(n, { long: true });
exports.KB = KB;
exports.bytes = bytes;
exports.duration = duration;
Notice what Rollup did:
- Scope hoisting:
bytes.jsandindex.jsbecame one flat module, no wrappers. external: ['ms']: the dependency stayed animport/require. A library must not inline its dependencies: the consumer's package manager installs them (and dedupes them with everyone else's copy).- Format conversion: the CJS file has
'use strict', arequire('ms'), andexports.x = …assignments, generated from the same ES module source.
Consuming both formats
mkdir -p units/src && cd units
cat > package.json <<'JSON'
{ "name": "@learner/units", "version": "1.0.0", "type": "module",
"exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.cjs" } },
"main": "./dist/index.cjs", "files": ["dist"], "dependencies": { "ms": "^2.1.3" },
"scripts": { "build": "rollup -c", "prepack": "npm run build" } }
JSON
npm install > /dev/null && npm install -D rollup@4.65.0 > /dev/null 2>&1
echo 'export const KB = 1024; export const bytes = (n) => `${n / 1024} KB`;' > src/bytes.js
printf 'import ms from "ms";\nexport { bytes, KB } from "./bytes.js";\nexport const duration = (n) => ms(n, { long: true });\n' > src/index.js
printf 'export default { input: "src/index.js", external: ["ms"], output: [ { file: "dist/index.js", format: "es" }, { file: "dist/index.cjs", format: "cjs", exports: "named" } ] };\n' > rollup.config.js
npm publish 2>&1 | grep -E 'dist/|^\+'
mkdir ../app-cjs ../app-esm
cd ../app-cjs && npm init -y > /dev/null && npm install @learner/units > /dev/null
node -e 'const u = require("@learner/units"); console.log("CJS:", u.bytes(2048), "|", u.duration(7200000))'
cd ../app-esm && npm init -y > /dev/null && npm pkg set type=module && npm install @learner/units > /dev/null
node --input-type=module -e 'import { bytes, duration } from "@learner/units"; console.log("ESM:", bytes(4096), "|", duration(3600000))'src/index.js → dist/index.js, dist/index.cjs...
created dist/index.js, dist/index.cjs in 25ms
npm notice 214B dist/index.cjs
npm notice 159B dist/index.js
+ @learner/units@1.0.0
CJS: 2 KB | 2 hours
ESM: 4 KB | 1 hour
prepack ran the build during npm publish, the tarball contains only dist/, and the exports map sent require to the CJS file and import to the ESM file.
Note: Shipping two formats has a cost: if one app loads the package through both
requireandimport, it gets two module instances (the "dual package hazard"), with separate state. Stateless utility libraries don't care; libraries with module-level state (a registry, a cache, a class used withinstanceof) should keep the state in one file that both builds share, or ship ESM only. Node 22+ canrequire()ES modules, which makes ESM-only packages increasingly practical.
Several outputs at once: UMD for a script tag
mkdir -p umd/src && cd umd
npm init -y > /dev/null && npm pkg set type=module && npm install -D rollup@4.65.0 > /dev/null 2>&1
echo 'export const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));' > src/index.js
cat > rollup.config.js <<'JS'
export default {
input: 'src/index.js',
output: { file: 'dist/clamp.umd.cjs', format: 'umd', name: 'Clamp', banner: '/*! clamp v1.0.0 | MIT */' },
};
JS
npx rollup -c --silent
cat dist/clamp.umd.cjs
node -e 'console.log(require("./dist/clamp.umd.cjs").clamp(12, 0, 10))'/*! clamp v1.0.0 | MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Clamp = {}));
})(this, (function (exports) { 'use strict';
const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
exports.clamp = clamp;
}));
10
The .cjs extension matters here: the project has "type": "module", so Node would treat a .js file as an ES module and the UMD wrapper's exports check would fail. UMD detects its environment at runtime: CommonJS (module.exports), AMD (define), or a browser global (window.Clamp). It's mostly legacy today, but still useful for libraries that people drop into a page with a <script> tag.
Test yourself
Why does a library's Rollup config mark its dependencies as external?
- Rollup can't bundle node_modules
- So consumers' package managers install and deduplicate them instead of getting a private inlined copy
- To make the build slower
- External modules are minified better
What does one Rollup config with an output array produce?
- One file with all formats
- One output per entry in the array, from a single parse of the input
- An error
- Only the first output
What is the dual package hazard?
- Two lockfiles in one repo
- A package loaded via both require and import gets two separate module instances
- Publishing ESM and CJS to different registries
- Two versions of Rollup