Language: JavaScript
Build Tool / Bundler
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.
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.
npm install --save-dev rollupyarn add --dev rollupRollup 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.
// rollup.config.js
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
}
};Defines a basic Rollup configuration that takes `src/main.js` as input and outputs a CommonJS bundle to `dist/bundle.js`.
# Terminal
npx rollup -cRuns Rollup using the configuration file (`rollup.config.js`) to generate the bundle.
import babel from '@rollup/plugin-babel';
export default {
input: 'src/main.js',
output: { file: 'dist/bundle.js', format: 'cjs' },
plugins: [babel({ babelHelpers: 'bundled' })]
};Integrates Babel with Rollup to transpile modern JavaScript for compatibility with older environments.
// Only the used functions will be included in the bundle
import { usedFunction } from './utils';
usedFunction();Rollup removes unused exports automatically to reduce bundle size.
export default {
input: 'src/main.js',
output: [
{ file: 'dist/bundle.cjs.js', format: 'cjs' },
{ file: 'dist/bundle.esm.js', format: 'esm' }
]
};Generates both CommonJS and ES module bundles from the same source.
// Use dynamic imports for code splitting
import('./moduleA').then(module => { module.doSomething(); });Rollup can create multiple chunks when dynamic imports are used, optimizing load times.
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.