JavaScript API

vsync edited this page Jan 5, 2017 · 34 revisions

Rollup exports an object with a single method, rollup:

var rollup = require( 'rollup' );

// used to track the cache for subsequent bundles
var cache;

  // The bundle's starting point. This file will be
  // included, along with the minimum necessary code
  // from its dependencies
  entry: 'main.js',
  // If you have a bundle you want to re-use (e.g., when using a watcher to rebuild as files change),
  // you can tell rollup use a previous bundle as its starting point.
  // This is entirely optional!
  cache: cache
}).then( function ( bundle ) {
  // Generate bundle + sourcemap
  var result = bundle.generate({
    // output format - 'amd', 'cjs', 'es', 'iife', 'umd'
    format: 'cjs'

  // Cache our bundle for later use (optional)
  cache = bundle;

  fs.writeFileSync( 'bundle.js', result.code );

  // Alternatively, let Rollup do it for you
  // (this returns a promise). This is much
  // easier if you're generating a sourcemap
    format: 'cjs',
    dest: 'bundle.js'

rollup.rollup( options )

Returns a Promise that resolves with a bundle. The following options are supported (only entry is required):


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


Object A previous bundle. Use it to speed up subsequent bundles :).



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)
// app.js
import moment from 'moment';

setInterval( function () {
  var timeStr = moment().format( 'h:mm:ss a' );
  console.log( 'the time is ' + timeStr );
}, 1000 );

// build.js
import * as path from 'path';

  entry: 'app.js',
  external: [
    path.resolve( './src/special-file.js' ) 


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: ''

// bundle.js
define([''], function (d3) {

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



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


Array of plugin objects (or a single plugin object) – see Plugins for more information.

import { rollup } from 'rollup';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

  entry: 'main.js',
  plugins: [
    nodeResolve({ jsnext: true, main: true }),
    commonjs({ include: 'node_modules/**' })


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!


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


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'.


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


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

bundle.generate( options )

Returns a { code, map } object, where map is a sourcemap, assuming the sourceMap: true option is set. The following options are supported (none are required, but format is highly recommended):


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

  • amd – Asychronous Module Definition, used with module loaders like RequireJS
  • cjs – CommonJS, suitable for Node and Browserify/Webpack
  • es (default) – Keep the bundle as an ES module file
  • iife – A self-executing function, suitable for inclusion as a <script> tag
  • umd – Universal Module Definition, works as amd, cjs and iife all in one


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'];


String An ID to use for AMD/UMD bundles:

var code = bundle.generate({
  format: 'amd',
  moduleId: 'my-bundle'

// -> define('my-bundle',...


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

var code = bundle.generate({
  format: 'iife',
  moduleName: 'MyBundle'

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


Object of id: name pairs (e.g. with import Backbone from 'backbone', backbone is the id, Backbone is the global name, as in window.Backbone), used for UMD/IIFE bundles:

var code = bundle.generate({
  format: 'iife',
  moduleName: 'MyBundle',
  globals: {
    backbone: 'Backbone',
    underscore: '_'

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


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)

var code = bundle.generate({
  format: 'amd',
  indent: false


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.


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

var code = bundle.generate({
  format: 'cjs',
  banner: '/* my-library version ' + version + ' */',
  footer: '/* follow me on Twitter! @rich_harris */'


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

var code = bundle.generate({
  format: 'umd',
  intro: 'var ENVIRONMENT = "production";'


Whether to generate a sourcemap. If true, the return value from bundle.generate(...) will include a map property, which is a sourcemap with two methods:

  • map.toString() – shorthand for JSON.stringify( map )
  • map.toUrl() – generates a data URI, suitable for appending to a file


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.

var result = bundle.generate({
  format: 'cjs',
  sourceMap: true,
  sourceMapFile: '/path/to/my-package/dist/bundle.js'
});; // 'bundle.js'; // ['../src/main.js', '../src/foo.js', ...]

fs.writeFileSync( 'dist/bundle.js', result.code +
  '\n//#' );
fs.writeFileSync( 'dist/', );


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.

var result = bundle.generate({
  format: 'cjs',
  useStrict: false

bundle.write( options )

Similar to bundle.generate, except that it writes the file (and accompanying sourcemap file, if appropriate) to the file system. Returns a Promise.

The options are as per bundle.generate, with one additional required option, dest, and two slightly different options, sourceMap and sourceMapFile:


The file to write to. If options.sourceMap === true, two files will be created – dest and dest + '.map.


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.

// sourcemap as separate file (recommended) -
// creates bundle.js and
  dest: 'bundle.js',
  format: 'cjs',
  sourceMap: true

// inline sourcemap - creates bundle.js
  dest: 'bundle.js',
  format: 'cjs',
  sourceMap: 'inline'


This option is unnecessary, as it defaults to the value of dest.