XUtils

Rollup

Next-generation ES6 module bundler.


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 templates, rollup-starter-lib and rollup-starter-app, demonstrate common configuration options, and more detailed instructions are available throughout the 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 --name "myBundle" --file bundle.js

For Node.js:

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

For both browsers and Node.js:

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

Tree Shaking

In addition to enabling the use of ES modules, Rollup also statically analyzes and optimizes 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('node:utils');
var query = 'Rollup';
// use the ajax method of the utils object
utils.ajax('https://api.example.com?search=' + query).then(handleResponse);

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

// import the ajax function with an ES import statement
import { ajax } from 'node: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 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, ES-module-aware tools like Rollup and webpack will import the ES module version directly.

Backers

Thank you to all our backers! 🙏 [Become a backer]


Articles

  • coming soon...