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.
This guide explains Rollup from the basics, including installation, configuration, output formats, plugins, code splitting and production builds.
Table of Contents
- What Is Rollup?
- Why Use Rollup?
- JavaScript Modules
- How Rollup Works
- Installation
- Create a Project
- Command Line
- Configuration
- Output Formats
- Tree-Shaking
- Code Splitting
- Plugins
- External Dependencies
- Production Builds
- Rollup vs Webpack
- Rollup vs Vite
- Complete Example
- Useful Commands
- Best Practices
- FAQs
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:
- JavaScript libraries and reusable packages
- Frontend applications
- Component libraries
- Developer tools
- Packages that need multiple output formats
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.
- ES module support: Works with JavaScript imports and exports.
- Tree-shaking: Can remove unused code when static analysis permits.
- Code splitting: Can generate multiple chunks instead of one large bundle.
- Output formats: Supports several formats for different environments.
- Plugins: Extends the build process.
- Configuration: Allows developers to customize their builds.
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.
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
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
| Format | Common use |
|---|---|
es | Modern JavaScript modules |
cjs | CommonJS module environments |
iife | Browser scripts wrapped in an immediately invoked function |
umd | Libraries intended to support multiple module environments |
system | SystemJS-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.
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:
- Tree-shaking and code optimization
- Minification through a suitable plugin
- Code splitting for optional features
- Correct handling of external dependencies
- Source maps where useful
- Testing the generated files in the target environment
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
| Feature | Rollup | Webpack |
|---|---|---|
| Common use | Libraries and module bundling | Applications and broad asset bundling workflows |
| Tree-shaking | Supported | Supported |
| Code splitting | Supported | Supported |
| Plugins | Rollup plugin ecosystem | Webpack plugin ecosystem |
| Configuration | Flexible | Flexible |
Neither tool is best for every project. Compare the ecosystem, application requirements, existing configuration and team experience before choosing.
Rollup vs Vite
| Feature | Rollup | Vite |
|---|---|---|
| Main purpose | JavaScript bundling | Development server and build tooling |
| Development server | Not its primary purpose | A core feature |
| Plugins | Rollup plugin API | Vite plugin ecosystem, with compatibility for many Rollup-style plugins |
| Library builds | Well suited | Also 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
- Works with modern ES modules.
- Can remove unused code through tree-shaking.
- Useful for reusable JavaScript libraries.
- Supports several output formats.
- Provides a flexible plugin API.
- Supports multiple entry points and code splitting.
Limitations of Rollup
- Advanced configuration may be difficult for beginners.
- Some dependencies need additional plugins.
- It is a bundler, not a complete application development environment by itself.
- Large projects may need additional tools for testing, type-checking and development.
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
| Command | Purpose |
|---|---|
npx rollup --help | Display command-line options |
npx rollup src/main.js --file dist/bundle.js --format es | Build a single ES module output |
npx rollup -c | Build using the default configuration file |
npx rollup -c rollup.config.js | Build using a named configuration file |
npx rollup -c -w | Watch for changes and rebuild |
npm run build | Run the project's configured build script, if defined |
Rollup Best Practices
- Keep source files organized and use clear module names.
- Understand JavaScript imports and exports before adding complex configuration.
- Keep your configuration as simple as possible.
- Install plugins only when your project needs them.
- Mark library dependencies as external only when consumers can provide them.
- Use source maps when they are useful for debugging.
- Test every output format you publish.
- Check the generated files before deploying.
- Read plugin documentation and update dependencies carefully.
Rollup Learning Roadmap
- Learn JavaScript fundamentals.
- Understand
importandexport. - Learn Node.js and npm basics.
- Install Rollup in a test project.
- Practice input and output configuration.
- Learn output formats.
- Understand tree-shaking.
- Practice code splitting and dynamic imports.
- Add plugins when needed.
- Learn external dependencies.
- Build a small JavaScript library.
- Explore the Rollup plugin API.
Rollup Cheat Sheet
| Concept | Meaning |
|---|---|
| Rollup | JavaScript module bundler |
| Input | Entry module for the build |
| Output | Configuration for generated files |
| Tree-shaking | Removing unused code when safe and possible |
| Plugin | Extends the build process |
| Code splitting | Generating multiple output chunks |
| External | A dependency kept outside the bundle |
| ES | ES module output |
| CJS | CommonJS output |
| IIFE | Immediately invoked function output |
| UMD | Universal Module Definition output |
| Source map | Connects 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.
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.