Menu
rollup.js

Introduction

Overview

Rollup is a module bundler for JavaScript which compiles small pieces of code into a something larger and more complex, such as a library or application. It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD.

Quick Start Guide

Install with npm install --global rollup. Rollup can be used either through a command line interface with an optional configuration file, or else through its JavaScript API. Run rollup --help to see the available options and parameters. The starter project template demonstrates common configuration options, and more detailed instructions are available throughout this user guide.

Commands

These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js.

For browsers:

# compile to a <script> containing a self-executing function
$ rollup main.js --format iife --output bundle.js

For Node.js:

# compile to a CommonJS module
$ rollup main.js --format cjs --output bundle.js

For both browsers and Node.js:

# UMD format requires a bundle name
$ rollup main.js --format umd --name "myBundle" --output bundle.js

Why

Developing software is usually easier if you break your project into smaller separate pieces, since that often removes unexpected interactions and dramatically reduces the complexity of the problems you'll need to solve, and simply writing smaller projects in the first place isn't necessarily the answer. Unfortunately, JavaScript has not historically included this capability as a core feature in the language.

This finally changed with the ES6 revision of JavaScript, which includes a syntax for importing and exporting functions and data so they can be shared between separate scripts. The specification is now fixed, but it is not yet implemented in browsers or Node.js. Rollup allows you to write your code using the new module system, and will then compile it back down to existing supported formats such as CommonJS modules, AMD modules, and IIFE-style scripts. This means that you get to write future-proof code, and you also get the tremendous benefits of...

Tree Shaking

In addition to enabling the use of ES6 modules, Rollup also statically analyzes the code you are importing, and will exclude anything that isn't actually used. This allows you to build on top of existing tools and modules without adding extra dependencies or bloating the size of your project.

For example, with CommonJS, the entire tool or library must be imported.

// import the entire utils object with CommonJS
var utils = require( 'utils' );
var query = 'Rollup';
// use the ajax method of the utils object
utils.ajax( 'https://api.example.com?search=' + query ).then( handleResponse );

But with ES6 modules, instead of importing the whole utils object, we can just import the one ajax function we need:

// import the ajax function with an ES6 import statement
import { ajax } from 'utils';
var query = 'Rollup';
// call the ajax function
ajax( 'https://api.example.com?search=' + query ).then( handleResponse );

Because Rollup includes the bare minimum, it results in lighter, faster, and less complicated libraries and applications. Since this approach is based on explicit import and export statements, it is vastly more effective than simply running an automated minifier to detect unused variables in the compiled output code.

ES6 modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries, without weighing down your project with all the other unused code. This will eventually be possible natively, but Rollup lets you do it today.

Compatibility

Importing CommonJS

Rollup can import existing CommonJS modules through a plugin.

Publishing ES6 Modules

To make sure your ES6 modules are immediately usable by tools that work with CommonJS such as Node.js and webpack, you can use Rollup to compile to UMD or CommonJS format, and then point to that compiled version with the main property in your package.json file. If your package.json file also has a module field, ES6-aware tools like Rollup and webpack 2 will import the ES6 module version directly.

Creating your first bundle

Before we begin, you'll need to have Node.js installed so that you can use npm. You'll also need to know how to access the command line on your machine.

The easiest way to use Rollup is via the Command Line Interface (or CLI). For now, we'll install it globally (later on we'll learn how to install it locally to your project so that your build process is portable, but don't worry about that yet). Type this into the command line:

npm install rollup --global # or `npm i rollup -g` for short

You can now run the rollup command. Try it!

rollup

Because no arguments were passed, Rollup prints usage instructions. This is the same as running rollup --help, or rollup -h.

Let's create a simple project:

mkdir -p my-rollup-project/src
cd my-rollup-project

First, we need an entry point. Paste this into a new file called src/main.js:

// src/main.js
import foo from './foo.js';
export default function () {
  console.log(foo);
}

Then, let's create the foo.js module that our entry point imports:

// src/foo.js
export default 'hello world!';

Now we're ready to create a bundle:

rollup src/main.js --format cjs

The --format option specifies what kind of bundle we're creating — in this case, CommonJS (which will run in Node.js). Because we didn't specify an output file, it will be printed straight to stdout:

'use strict';

var foo = 'hello world!';

var main = function () {
  console.log(foo);
};

module.exports = main;

You can save the bundle as a file like so:

rollup src/main.js --format cjs --output bundle.js
# or `rollup main.js -f cjs -o bundle.js`

(You could also do rollup src/main.js > bundle.js, but as we'll see later, this is less flexible if you're generating sourcemaps.)

Try running the code:

node
> var myBundle = require('./bundle.js');
> myBundle();
'hello world!'

Congratulations! You've created your first bundle with Rollup.

Using config files

So far, so good, but as we start adding more options it becomes a bit of a nuisance to type out the command.

To save repeating ourselves, we can create a config file containing all the options we need. A config file is written in JavaScript and is more flexible than the raw CLI.

Create a file in the project root called rollup.config.js, and add the following code:

// rollup.config.js
export default {
  entry: 'src/main.js',
  format: 'cjs',
  dest: 'bundle.js' // equivalent to --output
};

To use the config file, we use the --config or -c flag:

rm bundle.js # so we can check the command works!
rollup -c

You can override any of the options in the config file with the equivalent command line options:

rollup -c -o bundle-2.js # --output is equivalent to dest

(Note that Rollup itself processes the config file, which is why we're able to use export default syntax – the code isn't being transpiled with Babel or anything similar, so you can only use ES2015 features that are supported in the version of Node.js that you're running.)

You can, if you like, specify a different config file from the default rollup.config.js:

rollup --config rollup.config.dev.js
rollup --config rollup.config.prod.js

npm run build

Lots of JavaScript projects follow a simple convention: typing npm run build executes whatever build system the project uses. This is helpful because it means that someone who wants to help contribute to your project can dive right into the source code without knowing anything about the plumbing that ties it together (be that Rollup, or Webpack, or Gulp, or something more esoteric). They don't even need to install it globally like we did in the first section.

Setting up your own npm run build script is nice and straightforward.

Creating a package.json file

A package.json file contains important information about your project, including its name, version, license and dependencies. (In fact, you can't publish a package to npm without a package.json — but you should still have one if you're building an application rather than a library.)

The easiest way to create one is by running npm init inside the project folder and following the prompts.

Open the package.json and find (or create) the scripts section, and add a build entry:

{
  ...,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rollup -c"
  },
  ...
}

(This assumes you've got a rollup.config.js file in your project folder.)

Installing Rollup locally

Up till now we've been using a global installation of Rollup. It's much better to use a local installation, because then anyone cloning your project and running npm install will get a compatible version.

Run the following command...

npm install --save-dev rollup # or `npm i -D rollup`

...and notice that a devDependencies section has been added to your package.json:

{
  ...,
  "devDependencies": {
    "rollup": "^0.41.4"
  },
  ...
}

All of your npm run scripts will look for locally installed versions of commands like rollup if they exist.

Try running the script:

npm run build

Rebuilding when files change with npm run dev

By installing rollup-watch, you can create a script that automatically rebuilds your bundle whenever its source files change:

npm install --save-dev rollup-watch
{
  ...,
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rollup -c",
  "dev": "rollup -c -w"
  },
  ...
}

The command rollup -c -w (short for rollup --config --watch) runs Rollup in watch mode.

Getting started with plugins

So far, we've created a simple bundle from an entry point and a module imported via a relative path. As you build more complex bundles, you'll often need more flexibility – importing modules installed with npm, compiling code with Babel, working with JSON files and so on.

For that, we use plugins, which change the behaviour of Rollup at key points in the bundling process. A list of available plugins is maintained on the Rollup wiki.

Using plugins

For this tutorial, we'll use rollup-plugin-json, which allows Rollup to import data from a JSON file.

Install rollup-plugin-json as a development dependency:

npm install --save-dev rollup-plugin-json

(We're using --save-dev rather than --save because our code doesn't actually depend on the plugin when it runs – only when we're building the bundle.)

Update your src/main.js file so that it imports from your package.json instead of src/foo.js:

// src/main.js
import { version } from '../package.json';

export default function () {
  console.log('version ' + version);
}

Edit your rollup.config.js file to include the JSON plugin:

// rollup.config.js
import json from 'rollup-plugin-json';

export default {
  entry: 'src/main.js',
  format: 'cjs',
  plugins: [ json() ],
  dest: 'bundle.js'
};

Run Rollup with npm run build. The result should look like this:

'use strict';

var version = "1.0.0";

var main = function () {
  console.log('version ' + version);
};

module.exports = main;

(Notice that only the data we actually need gets imported – name and devDependencies and other parts of package.json are ignored. That's tree-shaking in action!)

Using Rollup with npm packages

At some point, it's very likely that your project will depend on packages installed from npm into your node_modules folder. Unlike other bundlers like Webpack and Browserify, Rollup doesn't know 'out of the box' how to handle these dependencies - we need to add some configuration.

Let's add a simple dependency called the-answer, which exports the answer to the question of life, the universe and everything:

npm install --save the-answer # or `npm i -S the-answer`

Notice that we used --save this time, so that it's stored in the dependencies section of package.json.

If we update our src/main.js file...

// src/main.js
import answer from 'the-answer';

export default function () {
  console.log('the answer is ' + answer);
}

...and run Rollup...

npm run build

...we'll see a warning like this:

⚠️ 'the-answer' is imported by src/main.js, but could not be resolved – treating it as an external dependency

The resulting bundle.js will still work in Node.js, because the import declaration gets turned into a CommonJS require statement, but the-answer does not get included in the bundle. For that, we need a plugin.

rollup-plugin-node-resolve

The rollup-plugin-node-resolve plugin teaches Rollup how to find external modules. Install it...

npm install --save-dev rollup-plugin-node-resolve

...and add it to your config file:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';

export default {
  entry: 'src/main.js',
  format: 'cjs',
  plugins: [ resolve() ],
  dest: 'bundle.js'
};

This time, when you npm run build, no warning is emitted — the bundle contains the imported module.

rollup-plugin-commonjs

Some libraries expose ES6 modules that you can import as-is — the-answer is one such module. But at the moment, the majority of packages on npm are exposed as CommonJS modules instead. Until that changes, we need to convert CommonJS to ES2015 before Rollup can process them.

The rollup-plugin-commonjs plugin does exactly that.

Note that rollup-plugin-commonjs should go before other plugins that transform your modules — this is to prevent other plugins from making changes that break the CommonJS detection.

Using Rollup with Babel

Many developers use Babel in their projects, so that they can use futuristic JavaScript features that aren't yet supported by browsers and Node.js.

The easiest way to use both Babel and Rollup is with rollup-plugin-babel. Install it:

npm i -D rollup-plugin-babel

Add it to rollup.config.js:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';

export default {
  entry: 'src/main.js',
  format: 'cjs',
  plugins: [
    resolve(),
    babel({
      exclude: 'node_modules/**' // only transpile our source code
    })
  ],
  dest: 'bundle.js'
};

Before Babel will actually compile your code, it needs to be configured. Create a new file, src/.babelrc:

{
  "presets": [
    ["latest", {
      "es2015": {
        "modules": false
      }
    }]
  ],
  "plugins": ["external-helpers"]
}

There are a few unusual things about this setup. First, we're setting "modules": false, otherwise Babel will convert our modules to CommonJS before Rollup gets a chance to do its thing, causing it to fail.

Secondly, we're using the external-helpers plugin, which allows Rollup to include any 'helpers' just once at the top of the bundle, rather than including them in every module that uses them (which is the default behaviour).

Thirdly, we're putting our .babelrc file in src, rather than the project root. This allows us to have a different .babelrc for things like tests, if we need that later – it's generally a good idea to have separate configuration for separate tasks.

Now, before we run rollup, we need to install the latest preset and the external-helpers plugin:

npm i -D babel-preset-latest babel-plugin-external-helpers

Running Rollup now will create a bundle... except we're not actually using any ES2015 features. Let's change that. Edit src/main.js:

// src/main.js
import answer from 'the-answer';

export default () => {
  console.log(`the answer is ${answer}`);
}

Run Rollup with npm run build, and check the bundle:

'use strict';

var index = 42;

var main = (function () {
  console.log('the answer is ' + index);
});

module.exports = main;

Sourcemaps

Sourcemaps can be enabled by adding the --sourcemap flag using the CLI, or by adding sourceMap: true to your configuration file.

export default {
  entry: 'src/main.js',
  format: 'umd',
  dest: 'bundle.js',
  sourceMap: true
};

Frequently asked questions

What is 'tree-shaking'?

Tree-shaking a.k.a. 'live code inclusion' is the process of only including the code that is used. It is similar to dead code elimination but can be more efficient. Read more about the origin of the name: Tree-shaking vs Dead-Code Elimination

Why are ES2015 modules better than AMD and CommonJS?

ES2015 modules are an official standard that will be arriving soon to browsers and Node.js. They allow static analysis that enables optimizations like tree-shaking, and have advanced features like circular references and live bindings.

Who made the Rollup logo? It's lovely.

I know! It was made by Julian Lloyd.

Comparison with other tools

coming soon...

Using RollupJS with Gulp

Rollup returns promises which are understood by gulp so integration is easy.

The syntax is very similar to the configuration file, but the properties are split across two different operations. Constructing the bundle, and transpiling to a target output.

var gulp = require('gulp'),
  rollup = require('rollup'),
  rollupTypescript = require('rollup-plugin-typescript')
;

gulp.task('build', function () {
  return rollup.rollup({
    entry: "./src/main.ts",
    plugins: [
      rollupTypescript()
    ],
  })
    .then(function (bundle) {
      bundle.write({
        format: "umd",
        moduleName: "library",
        dest: "./dist/library.js",
        sourceMap: true
      });
    })
});