Rollup in 2020
Published on July 24, 2020
Overview
Rollup is a module bundler. It compiles smaller pieces of Javascript into a single Javascript file. Besides compiling code it will also remove dead code(any unused code) if there is any. Rollup can also support code transformations. For example Typescript to Javascript.
Rollup released the same time when Javascript modules (ES6) happened. Rollup takes the advantage of these to compile code and remove any dead code.
Quick Start
Rollup is very easy to start. Use npx or global yarn/npm to install cli. Rollup can be used with an optional config or Javascript file.
For global install
yarn global add rollup.
Npx is preinstalled with node so you don’t have to install anything. Let’s use npx in this tutorial.
Compile
For ES6 and other supported environments
npx rollup index.js -o dist/bundle.js -f esm
**For Node **
npx rollup index.js -o dist/bundle.js -f cjs
For Browser
npx rollup index.js -o dist/bundle.js -f iife
**For Browser and Nodejs **
npx rollup index.js -o dist/bundle.js -f umd
By default -f will be esm if you don’t pass anything.
Dead code elimination (Tree Shaking)
Let’s create a sample source code.
create folder src
.
**src/math.js **
export const add = (a,b) => a + b;
export const multiply = (a,b) => a * b;
**src/index.js **
import { add } from './math';
console.log(add(a,b));
When compiled
npx rollup src/index.js -o dist/bundle.js
Now open dist/bundle.js
you will see
const add = (a,b) => a+b
console.log(add(1,2));
Notice here multiply
function is removed since it’s not used.
Rollup config
Now add rollup.config.js
to your project
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
}
};
This is same as npx rollup src/index.js -o dist/bundle.js -f cjs
.
To use config file
npx rollup -c
Rollup plugins
For more complex projects may need to handle different filetypes other than javascript. Do more operations on the source code. For that, we can use rollup plugins.
There is a huge collection of plugins available for rollup. https://github.com/rollup/awesome
Let’s add a terser
. It will minify the source code.
First, install the plugin.
yarn add rollup-plugin-teaser -D
Update rollup.config.js
import teaser from 'rollup-plugin-teaser';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
},
plugins:[teaser()]
}
Now, If you run npx rollup -c
you will see new minified Javascript bundle.