TechLearn Hub

Learn Technology, Programming and Web Development

Introduction

Modern JavaScript projects are often divided into many small modules. This makes code easier to organize, maintain and reuse. Before the project is distributed or deployed, however, its modules may need to be processed into suitable output files.

Rollup is a JavaScript module bundler that analyzes module relationships and generates bundles for applications and libraries. It is particularly well known for its support for ES modules and tree-shaking.

Simple definition: Rollup takes JavaScript modules, follows their imports and exports, and generates output files according to your build configuration.

This guide explains Rollup from the basics, including installation, configuration, output formats, plugins, code splitting and production builds.

What Is Rollup?

Rollup is a JavaScript module bundler. It starts with one or more entry modules, analyzes the files they import, and generates one or more output files.

Rollup is commonly used for:

Why Do Developers Use Rollup?

As projects grow, manually managing the files and dependencies needed for distribution becomes difficult. Rollup automates much of this process and provides control over how code is generated.

Understanding JavaScript Modules

A JavaScript module is a file that can export functions, variables or other values for use by another file.

Example: math.js

export function add(a, b) {
  return a + b;
}

Import the function in main.js

import { add } from "./math.js";

console.log(add(5, 3));

The import tells JavaScript that main.js depends on functionality exported by math.js. Rollup analyzes this relationship when building the project.

How Does Rollup Work?

In a simplified build, Rollup starts at the input file, follows module imports, analyzes the code, runs configured plugins and generates the requested output.

Source Files
     |
     v
Entry Module
     |
     v
Module Graph
     |
     v
Code Analysis
     |
     v
Plugins and Transformations
     |
     v
Output Generation
     |
     v
Bundle Files

The exact steps depend on the configuration and plugins. Tree-shaking is part of the code analysis and optimization process; it is not a guarantee that every unused-looking statement can always be removed.

Installing Rollup

You will need Node.js and npm installed in your development environment. Open a terminal in your project folder and run:

npm install --save-dev rollup

Installing Rollup locally as a development dependency is usually preferable for a project because its version is recorded in the project's dependency information.

Important: These terminal commands are intended for a Node.js development environment. You generally cannot run them directly inside a normal HTML page or the Acode editor without a suitable Node.js environment.

Creating a Simple Rollup Project

We will create a small project containing two JavaScript modules and a configuration file.

Step 1: Create the project

mkdir rollup-demo
cd rollup-demo
npm init -y

Step 2: Install Rollup

npm install --save-dev rollup

Step 3: Create the folders

mkdir src
mkdir dist

The dist directory is where our generated bundle will be placed. Create it before building with the examples that specify a file inside this directory.

Step 4: Create src/message.js

export function message() {
  return "Hello from Rollup!";
}

Step 5: Create src/main.js

import { message } from "./message.js";

console.log(message());

Using Rollup from the Command Line

Once Rollup is installed, you can run it using npx:

npx rollup src/main.js --file dist/bundle.js --format es

This command uses src/main.js as the entry module, writes the generated file to dist/bundle.js, and uses the ES module output format.

To see available command-line options, run:

npx rollup --help

Rollup Configuration

A configuration file lets you save build settings instead of typing them every time. A common filename is rollup.config.js.

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

Run the build with:

npx rollup -c
Configuration note: The ES module configuration above uses export default. Depending on your Node.js and package setup, you may need to configure your project to load the configuration as an ES module. Follow the current Rollup documentation if Node.js reports a configuration-loading error.

What Is Input?

The input option specifies the entry module or modules from which Rollup begins analyzing dependencies.

export default {
  input: "src/main.js"
};

Rollup follows imports from the entry module to discover related modules that belong to the build.

What Is Output?

The output option describes how the generated bundle should be written and which module format it should use.

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

For a single output bundle, file specifies the destination filename. For builds that generate multiple chunks, use an output directory with dir.

Rollup Output Formats

FormatCommon use
esModern JavaScript modules
cjsCommonJS module environments
iifeBrowser scripts wrapped in an immediately invoked function
umdLibraries intended to support multiple module environments
systemSystemJS-based environments

Choose a format according to how the generated file will be loaded. Some formats, including IIFE and UMD, have additional configuration requirements for certain builds.

ES module output

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

CommonJS output

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.cjs",
    format: "cjs"
  }
};

IIFE output

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "iife",
    name: "MyBundle"
  }
};

The IIFE format is useful for certain browser-script use cases. The output's dependencies and globals must still be configured correctly when external modules are used.

What Is Tree-Shaking?

Tree-shaking is the process of identifying code that is not needed by the final output and removing it where the module structure and code allow safe removal.

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

If an application imports only add, Rollup may be able to exclude the unused subtract and multiply exports from the output.

Remember: Tree-shaking can reduce bundle size, but the result depends on the code, side effects and build configuration.

Understanding Dead Code

Dead code is code that is not needed for a particular execution path or generated output. Rollup's static analysis can remove some unused exports, but it cannot safely remove every statement that appears unused. Code with side effects needs particular care.

What Is Code Splitting?

Code splitting allows Rollup to generate multiple output chunks instead of putting all code into one file. This can help applications load code only when it is required.

Dynamic imports are one way to create split points:

import("./dashboard.js")
  .then((module) => {
    module.start();
  })
  .catch((error) => {
    console.error("Could not load dashboard:", error);
  });

When the build is configured for code splitting, Rollup can place the dynamically imported module into a separate chunk.

Using Dynamic Imports

The import() expression loads a module asynchronously. It is useful when a feature does not need to be loaded immediately.

button.addEventListener("click", async () => {
  try {
    const module = await import("./settings.js");
    module.openSettings();
  } catch (error) {
    console.error("Could not load settings:", error);
  }
});

Code splitting is especially helpful when a project has optional screens or features. It does not automatically guarantee faster performance; the loading strategy and application structure matter too.

Multiple Entry Points

A project can have several entry points. Use output.dir when the build can generate multiple files.

export default {
  input: {
    main: "src/main.js",
    admin: "src/admin.js"
  },
  output: {
    dir: "dist",
    format: "es"
  }
};

This pattern is useful when a project needs separate bundles for different pages, applications or library entry points.

What Are Rollup Plugins?

Plugins extend Rollup's build process. Depending on the plugin, they can help resolve packages, transform source files, process JSON, integrate TypeScript, replace values or minify output.

Plugins are installed as project dependencies and added to the configuration. Use the official documentation for each plugin because options and compatibility can change between releases.

Node Resolve Plugin

The node-resolve plugin helps Rollup locate packages imported from node_modules.

npm install --save-dev @rollup/plugin-node-resolve
import { nodeResolve } from "@rollup/plugin-node-resolve";

export default {
  input: "src/main.js",
  plugins: [
    nodeResolve()
  ],
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

CommonJS Plugin

Some dependencies use CommonJS rather than ES module syntax. The CommonJS plugin can help Rollup process supported CommonJS modules.

npm install --save-dev @rollup/plugin-commonjs
import commonjs from "@rollup/plugin-commonjs";

export default {
  input: "src/main.js",
  plugins: [
    commonjs()
  ],
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

For projects that use both Node-style package imports and CommonJS dependencies, developers often configure both the node-resolve and CommonJS plugins.

JSON Plugin

To import JSON files as JavaScript modules, you can use the JSON plugin.

npm install --save-dev @rollup/plugin-json
import json from "@rollup/plugin-json";

export default {
  input: "src/main.js",
  plugins: [
    json()
  ],
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

TypeScript and Babel

Rollup can be integrated with TypeScript and Babel through suitable plugins. TypeScript projects may need type-checking as a separate step, depending on the selected build setup. Babel can transform JavaScript syntax for target environments.

Install and configure plugins that match your project rather than adding every plugin by default.

External Dependencies

The external option tells Rollup to leave specified dependencies outside the generated bundle. This is common when publishing libraries that expect consumers to provide certain dependencies.

export default {
  input: "src/main.js",
  external: ["react"],
  output: {
    file: "dist/library.js",
    format: "es"
  }
};

Marking a dependency as external does not automatically make it available at runtime. The environment consuming the bundle must provide that dependency in a compatible way.

Building JavaScript Libraries

Rollup is widely used for building reusable JavaScript packages. A library might provide different output formats for different consumers.

dist/
├── library.js
├── library.cjs
└── library.min.js

This is an illustrative layout. Your actual filenames and formats should match your package configuration and the environments you intend to support.

Understanding package.json

The package.json file describes a Node.js project or package, including its name, version, scripts and dependencies.

{
  "name": "my-library",
  "version": "1.0.0",
  "scripts": {
    "build": "rollup -c"
  },
  "devDependencies": {
    "rollup": "^4.0.0"
  }
}

The version shown is only an example of a version range, not a recommendation to use that exact version indefinitely. Install an appropriate current version and commit your lockfile when using version control.

After creating a build script, you can run:

npm run build

Watch Mode

Watch mode rebuilds the project when relevant files change. For a project with a configuration file, run:

npx rollup -c -w

This command watches for changes and reruns the configured build. Keep the terminal session open while developing.

Production Builds

A production build is intended for deployment or distribution. Depending on the project, a production workflow may include:

Minification

Minification can reduce file size by removing unnecessary characters and applying safe transformations. Rollup can work with a Terser-based plugin.

npm install --save-dev @rollup/plugin-terser
import terser from "@rollup/plugin-terser";

export default {
  input: "src/main.js",
  plugins: [
    terser()
  ],
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

Check the plugin's current documentation for the correct import style and options for your installed version.

Source Maps

Source maps help developers trace generated code back to the original source while debugging.

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "es",
    sourcemap: true
  }
};

Consider whether source maps should be published with your production files and whether they expose source code you intended to keep private.

Rollup vs Webpack

FeatureRollupWebpack
Common useLibraries and module bundlingApplications and broad asset bundling workflows
Tree-shakingSupportedSupported
Code splittingSupportedSupported
PluginsRollup plugin ecosystemWebpack plugin ecosystem
ConfigurationFlexibleFlexible

Neither tool is best for every project. Compare the ecosystem, application requirements, existing configuration and team experience before choosing.

Rollup vs Vite

FeatureRollupVite
Main purposeJavaScript bundlingDevelopment server and build tooling
Development serverNot its primary purposeA core feature
PluginsRollup plugin APIVite plugin ecosystem, with compatibility for many Rollup-style plugins
Library buildsWell suitedAlso supports library builds

Vite provides a broader development experience than Rollup alone. Its production bundling implementation can vary across major versions, so consult the current Vite documentation when working with a specific project.

Advantages of Rollup

Limitations of Rollup

Common Rollup Mistakes

1. Incorrect input path

Check that the entry file exists and that its path is correct relative to the project and configuration.

2. Missing plugins

Packages that use specific module formats or file types may need plugins. Read the error message and the dependency documentation.

3. Incorrect output format

Choose a format that matches the environment in which the bundle will run.

4. Missing output directory

If a command writes to dist/bundle.js, make sure the dist directory exists, or configure your build workflow to create it.

5. Incorrect external dependencies

If you mark a package as external, make sure the consumer can actually load it.

6. Assuming all unused code can be removed

Side effects and dynamic behavior can limit tree-shaking. Test the generated output instead of assuming it will always be smaller.

Complete Beginner Example

Use the following files to build a small project. This example assumes Rollup is installed and the src and dist directories exist.

Project structure

rollup-demo/
├── src/
│   ├── main.js
│   └── math.js
├── dist/
├── package.json
└── rollup.config.js

File: src/math.js

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

File: src/main.js

import { add } from "./math.js";

console.log("The answer is:", add(10, 5));

The program prints The answer is: 15 when the generated code is run in a compatible JavaScript environment. Since only add is imported, Rollup may exclude the unused multiply export.

File: rollup.config.js

export default {
  input: "src/main.js",
  output: {
    file: "dist/bundle.js",
    format: "es"
  }
};

Build the project

npx rollup -c

Open the generated file at dist/bundle.js to inspect the output. You can then test it in an environment that supports ES modules.

Rollup JavaScript API

Rollup also offers a JavaScript API that other Node.js scripts and tools can use to control the build process programmatically.

import { rollup } from "rollup";

const bundle = await rollup({
  input: "src/main.js"
});

try {
  await bundle.write({
    file: "dist/bundle.js",
    format: "es"
  });
} finally {
  await bundle.close();
}

This example uses top-level await, which requires a compatible Node.js module environment. For ordinary projects, the command line and configuration file are often simpler to start with.

Understanding a Simple Plugin

A Rollup plugin can define hooks that run during different stages of the build. The following example illustrates the basic shape of a plugin:

export default function myPlugin() {
  return {
    name: "my-plugin",

    transform(code, id) {
      return code;
    }
  };
}

This example does not change the code. Real plugins may transform source files, resolve modules or perform other build tasks. A production plugin should follow Rollup's plugin API and handle relevant file types carefully.

Useful Rollup Commands

CommandPurpose
npx rollup --helpDisplay command-line options
npx rollup src/main.js --file dist/bundle.js --format esBuild a single ES module output
npx rollup -cBuild using the default configuration file
npx rollup -c rollup.config.jsBuild using a named configuration file
npx rollup -c -wWatch for changes and rebuild
npm run buildRun the project's configured build script, if defined

Rollup Best Practices

Rollup Learning Roadmap

  1. Learn JavaScript fundamentals.
  2. Understand import and export.
  3. Learn Node.js and npm basics.
  4. Install Rollup in a test project.
  5. Practice input and output configuration.
  6. Learn output formats.
  7. Understand tree-shaking.
  8. Practice code splitting and dynamic imports.
  9. Add plugins when needed.
  10. Learn external dependencies.
  11. Build a small JavaScript library.
  12. Explore the Rollup plugin API.

Rollup Cheat Sheet

ConceptMeaning
RollupJavaScript module bundler
InputEntry module for the build
OutputConfiguration for generated files
Tree-shakingRemoving unused code when safe and possible
PluginExtends the build process
Code splittingGenerating multiple output chunks
ExternalA dependency kept outside the bundle
ESES module output
CJSCommonJS output
IIFEImmediately invoked function output
UMDUniversal Module Definition output
Source mapConnects generated code to original source for debugging

Frequently Asked Questions

Is Rollup a programming language?

No. Rollup is a JavaScript module bundler and build tool.

Is Rollup only for JavaScript?

Rollup focuses on JavaScript modules. Plugins can help process or transform other file types as part of a build.

What is tree-shaking?

Tree-shaking identifies and removes code that is not needed in the generated output when static analysis and the code's side effects allow it.

Can Rollup build libraries?

Yes. Building reusable JavaScript libraries and generating different output formats are common Rollup use cases.

Can Rollup bundle web applications?

Yes. Rollup can bundle web applications, although many developers choose higher-level tools for additional development features.

Does Rollup support code splitting?

Yes. Multiple entry points and dynamic imports can be used to produce multiple output chunks.

What is rollup.config.js?

It is a configuration file that tells Rollup how to build a project, including its entry points, plugins and output settings.

Is Rollup the same as Webpack?

No. Both are bundling tools, but they differ in their design, ecosystems and typical workflows.

Is Rollup the same as Vite?

No. Rollup is a bundler. Vite provides a broader development environment, including a development server and a build workflow.

Do I need plugins to use Rollup?

Not always. Simple projects can work without plugins. Add plugins when you need package resolution, file transformation or other functionality.

Conclusion

Rollup is a useful JavaScript module bundler for projects that need organized modules and configurable output files. Understanding its entry points, output formats, tree-shaking, plugins and code splitting gives you a solid foundation for building JavaScript applications and libraries.

Your next step: Create a project with main.js and math.js, install Rollup, configure the input and output, and run npx rollup -c. Inspect the generated bundle and experiment with one change at a time.