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. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. This will eventually be possible natively everywhere, but Rollup lets you do it today.

Quick start

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 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 only implemented in modern browsers and not finalised in 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 ES 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.

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

Compatibility

Importing CommonJS

Publishing ES Modules

To make sure your ES 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, ESM-aware tools like Rollup and webpack 2+ will import the ES module version directly.

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

You can export an array from your config file to build bundles from several different unrelated inputs at once, even in watch mode. To build different bundles with the same input, you supply an array of output options for each input:

You can also export a function that returns any of the above configuration formats. This function will be passed the current command line arguments so that you can dynamically adapt your configuration to respect e.g. --silent. You can even define your own command line options if you prefix them with config:

The flags listed below are only available via the command line interface. All other flags correspond to and override their config file equivalents, see the big list of options for details.

-h/--help

Print the help document.

-v/--version

Print the installed version number.

-w/--watch

Rebuild the bundle when its source files change on disk.

--silent

Don't print warnings to the console.

--environment <values>

Pass additional settings to the config file via process.ENV.

rollup -c --environment INCLUDE_DEPS,BUILD:production

will set process.env.INCLUDE_DEPS === 'true' and process.env.BUILD === 'production'. You can use this option several times. In that case, subsequently set variables will overwrite previous definitions. This enables you for instance to overwrite environment variables in package.json scripts:

then the config file will receive process.env.INCLUDE_DEPS === 'true' and process.env.BUILD === 'development'.

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.

rollup.rollup

The rollup.rollup function returns a Promise that resolves to a bundle object with various properties and methods shown here:

rollup.watch

Rollup also provides a rollup.watch function that rebuilds your bundle when it detects that the individual modules have changed on disk. It is used internally when you run Rollup from the command line with the --watch flag.

See above for details on inputOptions and outputOptions, or consult the big list of options for info on chokidar, include and exclude.

ES Module Syntax

The following is intended as a lightweight reference for the module behaviors defined in the ES2015 specification, since a proper understanding of the import and export statements are essential to the successful use of Rollup.

Importing

Imported values cannot be reassigned, though imported objects and arrays can be mutated (and the exporting module, and any other importers, will be affected by the mutation). In that way, they behave similarly to const declarations.

Named Imports

Import a specific item from a source module, with its original name.

import { something } from'./module.js';

Import a specific item from a source module, with a custom name assigned upon import.

import { something as somethingElse } from'./module.js';

Namespace Imports

Import everything from the source module as an object which exposes all the source module's named exports as properties and methods.

import * asmodulefrom'./module.js'

The something example from above would then be attached to the imported object as a property, e.g. module.something. If present, the default export can be accessed via module.default.

Default Import

Import the default export of the source module.

import something from'./module.js';

Empty Import

Load the module code, but don't make any new objects available.

import'./module.js';

This is useful for polyfills, or when the primary purpose of the imported code is to muck about with prototypes.

Tutorial

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:

The -f option (short for --format) 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:

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

Using 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 awesome plugins is maintained on the Rollup Awesome List.

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

Create a file in the project root called package.json, and add the following content:

Rollup will use the dynamic import to create a separate chunk that is only loaded on demand. In order for Rollup to know where to place the second chunk, instead of passing the --file option we set a folder to output to with the --dir option:

rollup src/main.js -f cjs -d dist

This will create a folder dist containing two files, main.js and chunk-[hash].js, where [hash] is a content based hash string. You can supply your own naming patterns by specifying the output.chunkFileNames and output.entryFileNames options.

You can still run your code as before with the same output, albeit a little slower as loading and parsing of ./foo.js will only commence once we call the exported function for the first time.

node -e "require('./dist/main.js')()"

If we do not use the --dir option, Rollup will again print the chunks to stdout, adding comments to highlight the chunk boundaries:

This is very useful if you want to load and parse expensive features only once they are used.

A different use for code-splitting is the ability to specify several entry points that share some dependencies. Again we extend our example to add a second entry point src/main2.js that statically imports src/foo.js just like we did in the original example:

Notice how both entry points import the same shared chunk. Rollup will never duplicate code and instead create additional chunks to only ever load the bare minimum necessary. Again, passing the --dir option will write the files to disk.

You can build the same code for the browser via native ES modules, an AMD loader or SystemJS.

See rollup-starter-code-splitting for an example on how to set up a web app that uses native ES modules on browsers that support them with a fallback to SystemJS if necessary.

Plugins

Plugins Overview

A Rollup plugin is an object with one or more of the properties and hooks described below, and which follows our conventions. A plugin should be distributed as a packages which exports a function that can be called with plugin specific options and returns such an object.

Plugins allow you to customise Rollup's behaviour by, for example, transpiling code before bundling, or finding third-party modules in your node_modules folder. For an example on how to use them, see Using plugins.

A Simple Example

The following plugin will intercept any imports of virtual-module without accessing the file system. This is for instance necessary if you want to use Rollup in a browser. It can even be used to replace entry points as shown in the example.

Conventions

Plugins should be tested. We recommend mocha or ava which support promises out of the box.

Use asynchronous methods when it is possible.

Document your plugin in English.

Make sure your plugin outputs correct source mappings if appropriate.

If your plugin uses 'virtual modules' (e.g. for helper functions), prefix the module ID with \0. This prevents other plugins from trying to process it.

Properties

name

Type: string

The name of the plugin, for use in error messages and warnings.

Hooks

In addition to properties defining the identity of your plugin, you may also specify properties that correspond to available build hooks. Hooks can affect how a build is run, provide information about a build, or modify a build once complete. There are different kinds of hooks:

async: The hook can also return a promise resolving to the same type of value; otherwise, the hook is marked as sync

first: If several plugins implement this hook, the hooks are run sequentially until a hook returns a value other than null or undefined

sequential: If this hook returns a promise, then other hooks of this kind will only be executed once this hook has resolved

parallel: If this hook returns a promise, then other hooks of this kind will not wait for this hook to be resolved

generateBundle

Called at the end of bundle.generate() or immediately before the files are written in bundle.write(). To modify the files after they have been written, use the writeBundle hook. bundle provides the full list of files being written or generated along with their details:

options

Reads and replaces or manipulates the options object passed to rollup.rollup. Returning null does not replace anything. This is the only hook that does not have access to most plugin context utility functions as it is run before rollup is fully configured.

renderChunk

Can be used to transform individual chunks. Called for each Rollup output chunk file. Returning null will apply no transformations.

renderError

Type: (error: Error) => void Kind: async, parallel

Called when rollup encounters an error during bundle.generate() or bundle.write(). The error is passed to this hook. To get notified when generation completes successfully, use the generateBundle hook.

renderStart

Type: () => void Kind: async, parallel

Called initially each time bundle.generate() or bundle.write() is called. To get notified when generation has completed, use the generateBundle and renderError hooks.

resolveDynamicImport

Defines a custom resolver for dynamic imports. In case a dynamic import is not passed a string as argument, this hook gets access to the raw AST nodes to analyze. Returning null will defer to other resolvers and eventually to resolveId if this is possible; returning false signals that the import should be kept as it is and not be passed to other resolvers thus making it external. Note that the return value of this hook will not be passed to resolveId afterwards; if you need access to the static resolution algorithm, you can use this.resolveId(importee, importer) on the plugin context.

resolveId

Defines a custom resolver. A resolver can be useful for e.g. locating third-party dependencies. Returning null defers to other resolveId functions (and eventually the default resolution behavior); returning false signals that importee should be treated as an external module and not included in the bundle.

If you return an object, then it is possible to resolve an import to a different id while excluding it from the bundle at the same time. This allows you to replace dependencies with external dependencies without the need for the user to mark them as "external" manually via the external option:

transform

Can be used to transform individual modules. Note that in watch mode, the result of this hook is cached when rebuilding and the hook is only triggered again for a module id if either the code of the module has changed or a file has changed that was added via this.addWatchFile the last time the hook was triggered for this module.

watchChange

Type: (id: string) => void Kind: sync, sequential

Notifies a plugin whenever rollup has detected a change to a monitored file in --watch mode.

More properties may be supported in future, as and when they prove necessary.

Plugin Context

A number of utility functions and informational bits can be accessed from within most hooks via this:

this.addWatchFile(id: string) => void

Adds additional files to be monitored in watch mode so that changes to these files will trigger rebuilds. id can be an absolute path to a file or directory or a path relative to the current working directory. This context function can only be used in hooks during the build phase, i.e. in buildStart, load, resolveId, and transform.

Note: Usually in watch mode to improve rebuild speed, the transform hook will only be triggered for a given module if its contents actually changed. Using this.addWatchFile from within the transform hook will make sure the transform hook is also reevaluated for this module if the watched file changes.

In general, it is recommended to use this.addWatchfile from within the hook that depends on the watched file.

this.emitAsset(assetName: string, source: string) => string

Emits a custom file to include in the build output, returning its assetId. You can defer setting the source if you provide it later via this.setAssetSource(assetId, source). A string or Buffer source must be set for each asset through either method or an error will be thrown on generate completion.

this.error(error: string | Error, position?: number) => void

Structurally equivalent to this.warn, except that it will also abort the bundling process.

this.getAssetFileName(assetId: string) => string

Get the file name of an asset, according to the assetFileNames output option pattern.

this.getModuleInfo(moduleId: string) => ModuleInfo

Returns additional information about the module in question in the form

{
id, // the id of the module, for convenience
isExternal, // for external modules that are not included in the graph
importedIds // the module ids imported by this module
}

this.resolveId(importee: string, importer: string) => string

this.setAssetSource(assetId: string, source: string | Buffer) => void

Set the deferred source of an asset.

this.warn(warning: string | RollupWarning, position?: number )

Using this method will queue warnings for a build. These warnings will be printed by the CLI just like internally-generated warnings (except with the plugin name), or captured by custom onwarn handlers.

The warning argument can be a string or an object with (at minimum) a message property:

Use the second form if you need to add additional properties to your warning object. Rollup will augment the warning object with a plugin property containing the plugin name, code (PLUGIN_WARNING) and id (the file being transformed) properties.

The position argument is a character index where the warning was raised. If present, Rollup will augment the warning object with pos, loc (a standard { file, line, column } object) and frame (a snippet of code showing the error).

Asset URLs

To reference an asset URL reference from within JS code, use the import.meta.ROLLUP_ASSET_URL_[assetId] replacement. The following example represents emitting a CSS file for a module that then exports a URL that is constructed to correctly point to the emitted file from the target runtime environment.

Advanced Loaders

The load hook can optionally return a { code, ast } object. The ast must be a standard ESTree AST with start and end properties for each node.

Transformers

Transformer plugins (i.e. those that return a transform function for e.g. transpiling non-JS files) should support options.include and options.exclude, both of which can be a minimatch pattern or an array of minimatch patterns. If options.include is omitted or of zero length, files should be included by default; otherwise they should only be included if the ID matches one of the patterns.

The transform hook, if returning an object, can also include an ast property. Only use this feature if you know what you're doing. Note that only the last AST in a chain of transforms will be used (and if there are transforms, any ASTs generated by the load hook will be discarded for the transformed modules.)

Example Transformer

(Use rollup-pluginutils for commonly needed functions, and to implement a transformer in the recommended manner.)

Source Code Transformations

If a plugin transforms source code, it should generate a sourcemap automatically, unless there's a specific sourceMap: false option. Rollup only cares about the mappings property (everything else is handled automatically). If it doesn't make sense to generate a sourcemap, (e.g. rollup-plugin-string), return an empty sourcemap:

return {
code: transformedCode,
map: { mappings: '' }
};

If the transformation does not move code, you can preserve existing sourcemaps by returning null:

Frequently Asked Questions

Why are ES modules better than CommonJS Modules?

ES modules are an official standard and the clear path forward for JavaScript code structure, whereas CommonJS modules are an idiosyncratic legacy format that served as a stopgap solution before ES modules had been proposed. ES modules allow static analysis that helps with optimizations like tree-shaking, and provide advanced features like circular references and live bindings.

What Is "tree-shaking?"

Tree-shaking, also known as "live code inclusion," is the process of eliminating code that is not actually used in a given project. It is similar to dead code elimination but can be much more efficient.

How do I use Rollup in Node.js with CommonJS modules?

Rollup strives to implement the specification for ES modules, not necessarily the behaviors of Node.js, NPM, require(), and CommonJS. Consequently, loading of CommonJS modules and use of Node's module location resolution logic are both implemented as optional plugins, not included by default in the Rollup core. Just npm install the commonjs and node-resolve plugins and then enable them using a rollup.config.js file and you should be all set. If the modules import JSON files, you will also need the json plugin.

Why isn't node-resolve a built-in feature?

There are two primary reasons:

Philosophically, it's because Rollup is essentially a polyfill of sorts for native module loaders in both Node and browsers. In a browser, import foo from 'foo' won't work, because browsers don't use Node's resolution algorithm.

On a practical level, it's just much easier to develop software if these concerns are neatly separated with a good API. Rollup's core is quite large, and everything that stops it getting larger is a good thing. Meanwhile, it's easier to fix bugs and add features. By keeping Rollup lean, the potential for technical debt is small.

Is Rollup meant for building libraries or applications?

Rollup is already used by many major JavaScript libraries, and can also be used to build the vast majority of applications. However if you want to use code-splitting or dynamic imports with older browsers, you will need an additional runtime to handle loading missing chunks. We recommend using the SystemJS Production Build as it integrates nicely with Rollup's system format output and is capable of properly handling all the ES module live bindings and re-export edge cases. Alternatively, an AMD loader can be used as well.

Who made the Rollup logo? It's lovely.

Integrating Rollup With Other Tools

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 such as 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:

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.

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

rollup-plugin-commonjs

Some libraries expose ES 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.

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

{
"presets": [
["@babel/env", {"modules": false}]
]
}

There are a few unusual elements to 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 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 babel-core and the env preset:

npm i -D @babel/core @babel/preset-env

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

Avoiding eval

You probably already know that 'eval is evil', at least according to some people. But it's particularly harmful with Rollup, because of how it works – unlike other module bundlers, which wrap each module in a function, Rollup puts all your code in the same scope.

That's more efficient, but it means that the shared scope is 'polluted' whenever you use eval, whereas with a different bundler, modules that didn't use eval would not be polluted. A minifier can't mangle variable names in polluted code, because it can't guarantee that the code to be evaluated doesn't reference those variable names.

Furthermore, it poses a security risk in that a malicious module could access another module's private variables with eval('SUPER_SEKRIT').

Luckily, unless you really do intend for the evaluated code to have access to local variables (in which case you're probably doing something wrong!), you can achieve the same effect in one of two ways:

eval2 = eval

Simply 'copying' eval provides you with a function that does exactly the same thing, but which runs in the global scope rather than the local one:

new Function

Using the Function constructor generates a function from the supplied string. Again, it runs in the global scope. If you need to call the function repeatedly, this is much, much faster than using eval.

Tree-shaking Doesn't Seem to be Working

Sometimes, you'll end up with code in your bundle that doesn't seem like it should be there. For example, if you import a utility from lodash-es, you might expect that you'll get the bare minimum of code necessary for that utility to work.

But Rollup has to be conservative about what code it removes in order to guarantee that the end result will run correctly. If an imported module appears to have side-effects, either on bits of the module that you're using or on the global environment, Rollup plays it safe and includes those side-effects.

Because static analysis in a dynamic language like JavaScript is hard, there will occasionally be false positives. Lodash is a good example of a module that looks like it has lots of side-effects, even in places that it doesn't. You can often mitigate those false positives by importing submodules (e.g. import map from 'lodash-es/map' rather than import { map } from 'lodash-es').

Rollup's static analysis will improve over time, but it will never be perfect in all cases – that's just JavaScript.

Error: "[name] is not exported by [module]"

Occasionally you will see an error message like this:

'foo' is not exported by bar.js (imported by baz.js)

Import declarations must have corresponding export declarations in the imported module. For example, if you have import a from './a.js' in a module, and a.js doesn't have an export default declaration, or import {foo} from './b.js', and b.js doesn't export foo, Rollup cannot bundle the code.

This error frequently occurs with CommonJS modules converted by rollup-plugin-commonjs, which makes a reasonable attempt to generate named exports from the CommonJS code but won't always succeed, because the freewheeling nature of CommonJS is at odds with the rigorous approach we benefit from in JavaScript modules. It can be solved by using the namedExports option, which allows you to manually fill in the information gaps.

Error: "this is undefined"

In a JavaScript module, this is undefined at the top level (i.e., outside functions). Because of that, Rollup will rewrite any this references to undefined so that the resulting behaviour matches what will happen when modules are natively supported.

There are occasional valid reasons for this to mean something else. If you're getting errors in your bundle, you can use options.context and options.moduleContext to change this behaviour.

Warning: "Sourcemap is likely to be incorrect"

You'll see this warning if you generate a sourcemap with your bundle (sourceMap: true or sourceMap: 'inline') but you're using one or more plugins that transformed code without generating a sourcemap for the transformation.

Usually, a plugin will only omit the sourcemap if it (the plugin, not the bundle) was configured with sourceMap: false – so all you need to do is change that. If the plugin doesn't generate a sourcemap, consider raising an issue with the plugin author.

Warning: "Treating [module] as external dependency"

Rollup will only resolve relative module IDs by default. This means that an import statement like this...

import moment from'moment';

...won't result in moment being included in your bundle – instead, it will be an external dependency that is required at runtime. If that's what you want, you can suppress this warning with the external option, which makes your intentions explicit:

Big list of options

Core functionality

external

Either a function that takes an id and returns true (external) or false (not external), or an Array of module IDs that should remain external to the bundle. The IDs should be either:

the name of an external dependency, exactly the way it is written in the import statement. I.e. to mark import "dependency.js" as external, use "dependency.js" while to mark import "dependency" as external, use "dependency".

input

The bundle's entry point(s) (e.g. your main.js or app.js or index.js). If you provide an array of entry points or an object mapping names to entry points, they will be bundled to separate output chunks. Unless the output.file option is used, generated chunk names will follow the output.entryFileNames option. When using the object form, the [name] portion of the file name will be the name of the object property while for the array form, it will be the file name of the entry point.

This will generate at least two entry chunks with the names entry-a.js and entry-b.js:

output.name

Type: string CLI: -n/--name <variableName>

Necessary for iife/umd bundles that exports values in which case it is the global variable name representing your bundle. Other scripts on the same page can use this variable name to access the exports of your bundle.

plugins

Type: Plugin | (Plugin | void)[]

See Using plugins for more information on how to use plugins and Plugins on how to write your own (try it out, it's not as difficult as it may sound and very much extends what you can do with Rollup!). For plugins imported from packages, remember to call the imported plugin function (i.e. commonjs(), not just commonjs). Falsy plugins will be ignored, which can be used to easily activate or deactivate plugins.

(This example also demonstrates how to use an async IIFE and dynamic imports to avoid unnecessary module loading, which can be surprisingly slow.)

Advanced functionality

cache

Type: RollupCache | false

The cache property of a previous bundle. Use it to speed up subsequent builds in watch mode — Rollup will only reanalyse the modules that have changed. Setting this option explicitly to false will prevent generating the cache property on the bundle and also deactivate caching for plugins.

inlineDynamicImports

This will inline dynamic imports instead of creating new chunks to create a single bundle. Only possible if a single input is provided.

manualChunks

Type: { [chunkAlias: string]: string[] }

Allows the creation of custom shared common chunks. Provides an alias for the chunk and the list of modules to include in that chunk. Modules are bundled into the chunk along with their dependencies. If a module is already in a previous chunk, then the chunk will reference it there. Modules defined into chunks this way are considered to be entry points that can execute independently to any parent importers.

Note that manual chunks can change the behaviour of the application if side-effects are triggered before the corresponding modules are actually used.

onwarn

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

The function receives two arguments: the warning object and the default handler. Warnings objects have, at a minimum, a code and a message property, allowing you to control how different kinds of warnings are handled. Other properties are added depending on the type of warning.

output.banner/output.footer

A string to prepend/append to the bundle. You can also supply a function that returns a Promise that resolves to a string to generate it asynchronously (Note: banner and footer options will not break sourcemaps).

output.extend

Type: boolean CLI: --extend/--no-extend Default: false

Whether or not to extend the global variable defined by the name option in umd or iife formats. When true, the global variable will be defined as (global.name = global.name || {}). When false, the global defined by name will be overwritten like (global.name = {}).

output.interop

Type: boolean CLI: --interop/--no-interop Default: true

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 is necessary to distinguish between default and named exports. This generally only applies if your external dependencies were transpiled (for example with Babel) – if you are sure you do not need it, you can save a few bytes with interop: false.

output.sourcemapExcludeSources

If true, the actual code of the sources will not be added to the sourcemaps making them considerably smaller.

output.sourcemapFile

Type: string CLI: --sourcemapFile <file-name-with-path>

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 not required if output is specified, in which case an output filename will be inferred by adding ".map" to the output filename for the bundle.

output.sourcemapPathTransform

Type: (sourcePath: string) => string

A transformation to apply to each path in a sourcemap. For instance the following will change all paths to be relative to the src directory.

preserveModules

Instead of creating as few chunks as possible, this mode will create separate chunks for all modules using the original module names as file names. Requires the output.dir option. Tree-shaking will still be applied, suppressing files that are not used by the provided entry points or do not have side-effects when executed. This mode can be used to transform a file structure to a different module format.

Danger zone

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

acorn

Type: AcornOptions

Any options that should be passed through to Acorn's parse function, such as allowReserved: true. Cf. the Acorn documentation for more available options.

acornInjectPlugins

Type: AcornPluginFunction | AcornPluginFunction[]

A single plugin or an array of plugins to be injected into Acorn. For instance to use JSX syntax, you can specify

output.noConflict

Type: boolean CLI: --noConflict/--no-noConflict Default: false

This will generate an additional noConflict export to UMD bundles. When called in an IIFE scenario, this method will return the bundle exports while restoring the corresponding global variable to its previous value.

output.preferConst

Type: boolean CLI: --preferConst/--no-preferConst Default: false

Generate const declarations for exports rather than var declarations.

output.strict

Type: boolean CLI: --strict/--no-strict Default: true

Whether to include the 'use strict' pragma at the top of generated non-ESM bundles. Strictly-speaking, ES modules are always in strict mode, so you shouldn't disable this without good reason.

output.dynamicImportFunction

Type: string CLI: --dynamicImportFunction <name> Default: import

This will rename the dynamic import function to the chosen name when outputting ESM bundles. This is useful for generating code that uses a dynamic import polyfill such as this one.

preserveSymlinks

Type: boolean CLI: --preserveSymlinks Default: false

When set to false, symbolic links are followed when resolving a file. When set to true, instead of being followed, symbolic links are treated as if the file is where the link is. To illustrate, consider the following situation:

If preserveSymlinks is false, then the bundle created from /main.js will log "next to original" as it will use the location of the symbolically linked file to resolve its dependencies. If preserveSymlinks is true, however, it will log "next to linked" as the symbolic link will not be resolved.

shimMissingExports

If this option is provided, bundling will not fail if bindings are imported from a file that does not define these bindings. Instead, new variables will be created for these bindings with the value undefined.

treeshake

Whether or not to apply tree-shaking and to fine-tune the tree-shaking process. Setting this option to false will produce bigger bundles but may improve build performance. If you discover a bug caused by the tree-shaking algorithm, please file an issue! Setting this option to an object implies tree-shaking is enabled and grants the following additional options:

If false, assume reading a property of an object never has side-effects. Depending on your code, disabling this option can significantly reduce bundle size but can potentially break functionality if you rely on getters or errors from illegal property access.

If false, ignore hints from pure annotations, i.e. comments containing @__PURE__ or #__PURE__, when determining side-effects of function calls and constructor invocations. These annotations need to immediately precede the call invocation to take effect. The following code will be completely removed unless this option is set to false, in which case it will remain unchanged.

experimentalOptimizeChunks

Experimental feature to optimize chunk groupings. When a large number of chunks are generated, this allows smaller chunks to group together as long as they are within the chunkGroupingSize limit. It results in unnecessary code being loaded in some cases in order to have a smaller number of chunks overall. Disabled by default as it may cause unwanted side effects when loading unexpected code.

perf

Type: boolean CLI: --perf/--no-perf Default: false

Whether to collect performance timings. When used from the command line or a configuration file, detailed measurements about the current bundling process will be displayed. When used from the JavaScript API, the returned bundle object will contain an aditional getTimings() function that can be called at any time to retrieve all accumulated measurements.

For each key, the first number represents the elapsed time while the second represents the change in memory consumption and the third represents the total memory consumption after this step. The order of these steps is the order used by Object.keys. Top level keys start with # and contain the timings of nested steps, i.e. in the example above, the 698ms of the # BUILD step include the 538ms of the ## parse modules step.

Watch options

These options only take effect when running Rollup with the --watch flag, or using rollup.watch.