What it is
Rollup is a JavaScript module bundler that compiles small pieces of code into something larger and more complex, such as a library or application. It uses ES modules to produce optimized, tree-shaken bundles.
Rollup takes ES module files as input, resolves dependencies, and outputs a single JavaScript file. It supports plugins for handling non-JS files, Babel transpilation, and other transformations. Rollup is particularly good for building libraries that are shared across projects.
Installation
npm install --save-dev rollupGetting started
The smallest useful thing you can do with it, and what each part means.
// rollup.config.js
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
}
};# Terminal
npx rollup -cAdvanced usage
Where the library earns its place over a simpler alternative.
import babel from '@rollup/plugin-babel';
export default {
input: 'src/main.js',
output: { file: 'dist/bundle.js', format: 'cjs' },
plugins: [babel({ babelHelpers: 'bundled' })]
};// Only the used functions will be included in the bundle
import { usedFunction } from './utils';
usedFunction();export default {
input: 'src/main.js',
output: [
{ file: 'dist/bundle.cjs.js', format: 'cjs' },
{ file: 'dist/bundle.esm.js', format: 'esm' }
]
};// Use dynamic imports for code splitting
import('./moduleA').then(module => { module.doSomething(); });Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Could not resolve import
- Check file paths and use appropriate plugins like `@rollup/plugin-node-resolve` for node_modules imports.
- Unexpected token in JSON
- Use plugins like `@rollup/plugin-json` to import JSON files.
- Bundle is too large
- Ensure tree-shaking works correctly and consider splitting code into multiple chunks using dynamic imports.
Best practices
- Use ES modules for cleaner and more tree-shakable code.
- Leverage plugins for handling non-JS assets, transpilation, and optimizations.
- Keep Rollup configuration modular and reusable.
- Use multiple output formats for library distribution (CJS, ESM, UMD).
- Enable source maps during development for easier debugging.
Background
Why it exists, and what it was reacting to.
Rollup was created to take advantage of ES module syntax in JavaScript and provide a more efficient bundling process compared to older tools. It became popular for bundling libraries because of its ability to generate clean, minimal output with tree-shaking to remove unused code.
