Menu
rollup.js

Introduction

Overview

Rollup is a module bundler for JavaScript which compiles small pieces of code into 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. ES6 modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. This will eventually be possible natively, but Rollup lets you do it today.

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.

See rollup-starter-lib and rollup-starter-app to see example library and application projects using Rollup

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.

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. You could also define the dev command as npm run build -- -w which just adds the watch flag to the build command.

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.

Peer dependencies

Let's say that you're building a library that has a peer dependency, such as React or Lodash. If you set up externals as described above, your rollup will bundle all imports:

import answer from 'the-answer';
import _ from 'lodash';

You can finely tune which imports are bundled and which are treated as external. For this example, we'll treat lodash as external, but not the-answer.

Here is the config file:

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

export default {
  entry: 'src/main.js',
  format: 'cjs',
  plugins: [resolve({
    // pass custom options to the resolve plugin
    customResolveOptions: {
      moduleDirectory: 'node_modules'
    }
  })],
  // indicate which modules should be treated as external
  external: ['lodash'],
  dest: 'bundle.js'
};

Voila, lodash will now be treated as external, and not be bundled with your library.

The external key accepts either an array of module names or a function which takes the module name and returns true if it should be treated as external. For example:

export default {
  // ...
  external: id => /lodash/.test(id)
}

You might use this form if you're using babel-plugin-lodash to cherry-pick lodash modules. In this case, Babel will convert your import statements to look like this:

import _merge from 'lodash/merge';

The array form of external does not handle wildcards, so this import will only be treated as external in the functional form.

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
};

Command Line Interface

Rollup should typically be used from the command line. You can provide an optional Rollup configuration file to simplify command line usage and enable advanced Rollup functionality.

Configuration Files

Rollup configuration files are optional, but they are powerful and convenient and thus recommended.

A config file is an ES6 module that exports a default object with the desired options. Typically, it is called rollup.config.js and sits in the root directory of your project.

// rollup.config.js
let configuration = {
  // configuration options go here...
};
export default configuration;

In some cases option names differ slightly between command line usage and configuration files.

You must use a configuration file in order to do any of the following:

To use Rollup with a configuration file, pass the --config or -c flags.

# use Rollup with a rollup.config.js file
$ rollup --config

# alternatively, specify a custom config file location
$ rollup --config my.config.js

Core Functionality

• --input / -i string (required)

The entry point file from which to start compilation and resolution of dependencies. This is likely identical to the module field in your package.json file.

From the command line:

# bundle app.js and all dependencies
$ rollup --input app.js

When specified in a configuration file, this option is known as entry instead of input:

let configuration = {
  entry: './app.js'
};

• --output / -o string (required)

The output filename into which to save the bundle.

From the command line:

# bundle app.js and all dependencies
$ rollup --input app.js --output app-bundled.js

When specified in a configuration file, this option is known as dest instead of output:

// rollup.config.js
let configuration = {
  dest: './app-bundled.js'
};

• --format / -f string (required)

The target output format to bundle the input code into.

  • iife: an immediately-invoked function expression, typically used from within a <script> tag.
  • cjs: a CommonJS module like those popularized by Node.js, webpack, and browserify.
  • amd: an Asynchronous Module Definition as popularized by RequireJS.
  • umd: a Universal Module Definition which is usable either from within a <script> tag, as a CommonJS module, or as an AMD module. Because it's so flexible, this is the recommended option, but it requires that you also specify a module name as described below.
  • es: bundles your multiple ES6 modules into a single ES6 module.
# bundle app.js into iife format
$ rollup --input app.js --format iife
// rollup.config.js
let configuration = {
  entry: './app.js',
  format: 'iife'
};

• plugins array (configuration files only)

An array of Rollup plugins that should be used to transform the bundle code. The plugins are functions when imported, but the functions must to be called in order for the plugin to work.

For example, to enable import of CommonJS modules such as those from the Node.js ecosystem, add the following to your Rollup configuration file:

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

let configuration = {
  plugins: [
    resolve(),
    commonjs()
  ]
};
export default configuration;

• --name / -n string

A module name is required when you are bundling to a UMD module. This string will be used as the global variable name of the module when it is loaded in a browser through a <script> tag.

# bundle app.js to UMD format
$ rollup --input app.js --format umd --name mymodule
// rollup.config.js
let configuration = {
  entry: './app.js',
  format: 'umd',
  name: 'mymodule'
};

• --sourcemap / -m string

Generates a sourcemap which maps the output bundle back to the input source code, so that error messages and console.log calls will report the original line number.

  • inline: the sourcemap will be embedded in the existing output file as a data URI.
  • true: the sourcemap will be created in a separate file, by default named after whatever output filename is specified with --output/dest. You can also specify an alternate filename for the sourcemap using the --sourcemapfile option.

If you don't pass a value for this option, it defaults to true.

# bundle app.js to iife format with inline sourcemap included
$ rollup --input app.js --format iife --sourcemap inline

When specified in a configuration file, this this property name should be camelCased.

// rollup.config.js
let configuration = {
  sourceMap: 'inline'
};

JavaScript API

Rollup provides a JavaScript API which is usable from Node.js. You will rarely need to use this, and should probably be using the command line API unless you are extending Rollup itself or using it for something esoteric, such as generating bundles programmatically.

Including

Alas, Node doesn't yet natively support ES6 modules so you'll need to import Rollup as a CommonJS module using require(), even though that's off message for an ES6 module tool :(

let rollup = require('rollup');

Rollup exports an object which contains a single .rollup() method.

Input

rollup.rollup(inputOptions)

The rollup.rollup() method specifies the inputs passed to Rollup for compilation. It takes a single argument, which is an object containing one or more of the following properties, and it returns a Promise which resolves to the bundle object.

Input Options

The following properties can be added to your input options object to change the default behavior of the rollup.rollup() method:

• entry string (required)

The module's entry point file from which to start compilation and resolution of dependencies. This is likely identical to the module field in your package.json file.

let inputOptions = {
  entry: './app.js'
};

• plugins array

An array of Rollup plugins that should be used to transform the bundle code. The plugins are functions when imported, but the functions must to be called in order for the plugin to work.

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

let inputOptions = {
  plugins: [
    resolve(),
    commonjs()
  ]
};

• cache object

An optional variable representing the last bundle compiled by the current Node process. This is mostly useful for speeding up incremental rebuilds, such as when you're watching the files and rebuilding automatically on changes.

• onwarn function

A function which will intercept warning messages. If not supplied, warnings will just be deduplicated and printed to the console.

Warnings are objects with at minimum a code and a message property, letting you customize the handling for your needs.

let inputOptions = {
  onwarn: function(warning) {
    // skip certain warnings
    if ( warning.code === 'UNUSED_EXTERNAL_IMPORT' ) {
      return;
    }
    // throw other warnings
    if ( warning.code === 'NON_EXISTENT_EXPORT' ) {
      throw new Error( warning.message );
    }
    // console.warn everything else
    console.warn( warning.message );
  }
}

Many warnings also have loc and frame properties which can help you precisely locate the source of the problem that caused the warning. loc is a location object containing properties for the file, line of code and column where the error occurred, and frame is a string with the surrounding code.

let inputOptions = {
  onwarn: function(warning) {
    // print location if provided
    if (warning.loc) {
      console.warn(warning.loc.file + warning.loc.line + ':' + warning.loc.column);
    }
    // print surrounding code if provided
    if (warning.frame) {
      console.warn(warning.frame);
    }
    // generic logging of
    console.warn(warning.message);
  }
};

• paths object or function

Specifies paths of external files for use in the bundle. At the end of the build, the bundler will rewrite references to these modules so they use the external locations. For now this is only useful for AMD and UMD output formats and loading dependencies from a CDN, but eventually it will also be used for loading of remote ES6 modules.

When the paths property contains an object, it should consist of key-value pairs where the key is the module ID and the value is the remote location.

let inputOptions = {
  paths: {
    d3: 'https://d3js.org/d3.v4.min.js'
  }
};

When the paths property contains a function, it will be called for every module ID. If the function returns the original input ID, no remote loading is attempted; if it returns anything else, it will be treated as a string representing the remote location of the module.

let inputOptions = {
  paths: function(id) {
    if (id === 'd3') {
      return 'https://d3js.org/d3.v4.min.js';
    }
    return id;
  }
};

• acorn object

Any parameters that should be passed through to Acorn.

• context object

In ES6 modules, the this object is always undefined. In rare cases you might need to change this to something else, like window. Use of this option is discouraged.

• moduleContext object or function

When the moduleContext property contains an object, it should consist of key-value pairs where the key is the module ID and the value is the context object to use for that module.

When the moduleContext property contains a function, it will be called for every module ID. If the function returns a value, it will be treated as the value to be used as the this keyword for that module; otherwise, the value of the this context will be undefined as usual.

Use of this option is discouraged.

• legacy boolean

Adds support for very old environments like IE8 by stripping out more modern code that might not work reliably, at the cost of deviating slightly from the precise specifications required of ES6 module environments.

Output

The Promise returned by the rollup.rollup() method resolves to an object representing the compiled bundle.

• bundle.generate(config)

Compiles the project. Returns an object which contains properties for the compiled code (as a string) and the map (a sourcemap object). The optional configuration object argument is identical to the configuration object you might use in a configuration file for the command line, but any input options will be ignored because the inputs have already been supplied.

• bundle.write(config)

Compiles the project and writes the file to disk, returning a Promise which resolves when the write operation has completed. This requires a configuration object argument which specifies an output filename under the dest property.

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.

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

gulp.task('build', async function () {
  const bundle = await rollup.rollup({
    entry: './src/main.ts',
    plugins: [
      rollupTypescript()
    ]
  });

  await bundle.write({
    format: 'umd',
    moduleName: 'library',
    dest: './dist/library.js',
    sourceMap: true
  });
});

Big list of options

Core functionality

• entry (required)

String The bundle's entry point (e.g. your main.js or app.js or index.js)

• dest

String The file to write to.

• format (required)

String The format of the generated bundle. One of the following:

  • amd – Asynchronous Module Definition, used with module loaders like RequireJS
  • cjs – CommonJS, suitable for Node and Browserify/Webpack
  • es – Keep the bundle as an ES module file
  • iife – A self-executing function, suitable for inclusion as a <script> tag. (If you want to create a bundle for your application, you probably want to use this, because it leads to smaller file sizes.)
  • umd – Universal Module Definition, works as amd, cjs and iife all in one

• plugins

Array of plugin objects (or a single plugin object) – see Getting started with plugins for more information.

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

export default {
  entry: 'main.js',
  plugins: [
    resolve(),
    commonjs()
  ]
};

• sourceMap

If true, a separate sourcemap file will be created. If inline, the sourcemap will be appended to the resulting dest file as a data URI.

• sourceMapFile

String The location of the generated bundle. If this is an absolute path, all the sources paths in the sourcemap will be relative to it. The map.file property is the basename of sourceMapFile, as the location of the sourcemap is assumed to be adjacent to the bundle.

sourceMapFile is unnecessary if dest is specified.

Advanced functionality

• external

Either...

Function that takes an id and returns true (external) or false (not external), or...

Array of strings. A list of IDs of modules that should remain external to the bundle. The IDs should be either:

  1. the name of an external dependency
  2. a resolved ID (like an absolute path to a file)
// rollup.config.js
import path from 'path';

export default {
  ...,
  external: [
    'some-externally-required-library',
    path.resolve( './src/some-local-file-that-should-not-be-bundled.js' )
  ]
};

• paths

Function that takes an ID and returns a path, or Object of id: path pairs. Where supplied, these paths will be used in the generated bundle instead of the module ID, allowing you to (for example) load dependencies from a CDN:

// app.js
import { selectAll } from 'd3';
selectAll('p').style('color', 'purple');
// ...

// rollup.config.js
export default {
  src: 'app.js',
  dest: 'bundle.js',
  format: 'amd',
  external: ['d3'],
  paths: {
    d3: 'https://d3js.org/d3.v4.min'
  }
};

// bundle.js
define(['https://d3js.org/d3.v4.min'], function (d3) {

  d3.selectAll('p').style('color', 'purple');
  // ...

});

• banner/footer (configuration file only)

String A string to prepend/append to the bundle. (Note: banner and footer options will not break sourcemaps)

// rollup.config.js
export default {
  ...,
  banner: '/* my-library version ' + version + ' */',
  footer: '/* follow me on Twitter! @rich_harris */'
};

• intro/outro (configuration file only)

String Similar to banner and footer, except that the code goes inside any format-specific wrapper

export default {
  ...,
  intro: 'var ENVIRONMENT = "production";'
};

• cache

Object A previously-generated bundle. Use it to speed up subsequent builds

• onwarn (configuration file only)

Function that will intercept warning messages. If not supplied, warnings will be deduplicated and printed to the console.

Warnings are objects with at minimum a code and a message property, meaning you can control how different kinds of warnings are handled:

onwarn (warning) {
  // skip certain warnings
  if (warning.code === 'UNUSED_EXTERNAL_IMPORT') return;

  // throw on others
  if (warning.code === 'NON_EXISTENT_EXPORT') throw new Error(warning.message);

  // console.warn everything else
  console.warn(warning.message);
}

Many warnings also have a loc property and a frame allowing you to locate the source of the warning:

onwarn ({ loc, frame, message }) {
  // print location if applicable
  if (loc) {
    console.warn(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
    if (frame) console.warn(frame);
  } else {
    console.warn(message);
  }
}

• moduleName

String The name to use for the module for umd/iife bundles (required for bundles with exports):

// rollup.config.js
export default {
  ...,
  format: 'iife',
  moduleName: 'MyBundle'
};

// -> var MyBundle = (function () {...

• globals

Object of id: name pairs, used for umd/iife bundles. For example, in a case like this...

import $ from 'jquery';

...we want to tell Rollup that the jquery module ID equates to the global jQuery variable:

// rollup.config.js
export default {
  ...,
  format: 'iife',
  moduleName: 'MyBundle',
  globals: {
    jquery: 'jQuery'
  }
};

/*
var MyBundle = (function ($) {
  // code goes here
}(window.jQuery));
*/.

Alternatively, supply a function that will turn an external module ID into a global.

Danger zone

You probably don't need to use these options unless you know what you're doing!

• treeshake

Whether or not to apply tree-shaking. It's recommended that you omit this option (defaults to treeshake: true), unless you discover a bug caused by the tree-shaking algorithm in which case use treeshake: false once you've filed an issue!

• acorn

Any options that should be passed through to Acorn, such as allowReserved: true.

• context

By default, the context of a module – i.e., the value of this at the top level – is undefined. In rare cases you might need to change this to something else, like 'window'.

• moduleContext

Same as options.context, but per-module – can either be an object of id: context pairs, or an id => context function.

• legacy

Adds support for very old environments like IE8, at the cost of some extra code.

• exports

String What export mode to use. Defaults to auto, which guesses your intentions based on what the entry module exports:

  • default – suitable if you're only exporting one thing using export default ...
  • named – suitable if you're exporting more than one thing
  • none – suitable if you're not exporting anything (e.g. you're building an app, not a library)

The difference between default and named affects how other people can consume your bundle. If you use default, a CommonJS user could do this, for example:

var yourLib = require( 'your-lib' );

With named, a user would do this instead:

var yourMethod = require( 'your-lib' ).yourMethod;

The wrinkle is that if you use named exports but also have a default export, a user would have to do something like this to use the default export:

var yourMethod = require( 'your-lib' ).yourMethod;
var yourLib = require( 'your-lib' )['default'];

• amd (configuration file only?)

Object Can contain the following properties:

  • amd.id String An ID to use for AMD/UMD bundles:
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    id: 'my-bundle'
  }
};

// -> define('my-bundle', ['dependency'], ...
  • amd.define String A function name to use instead of define:
// rollup.config.js
export default {
  ...,
  format: 'amd',
  amd: {
    define: 'def'
  }
};

// -> def(['dependency'],...

• indent

String the indent string to use, for formats that require code to be indented (amd, iife, umd). Can also be false (no indent), or true (the default – auto-indent)

// rollup.config.js
export default {
  ...,
  indent: false
};

• interop

Boolean whether or not to add an 'interop block'. By default (interop: true), for safety's sake, Rollup will assign any external dependencies' default exports to a separate variable if it's necessary to distinguish between default and named exports. This generally only applies if your external dependencies were transpiled (for example with Babel) – if you're sure you don't need it, you can save a few bytes with interop: false.

• useStrict

true or false (defaults to true) – whether to include the 'use strict' pragma at the top of generated non-ES6 bundles. Strictly-speaking (geddit?), ES6 modules are always in strict mode, so you shouldn't disable this without good reason.