Rollup.js Module Bundler

0.58.4 · active · verified Sun Apr 19

Rollup is a highly optimized JavaScript module bundler that compiles small pieces of code into larger, more complex libraries or applications. It primarily leverages the standardized ES module format (ESM) for code, enabling advanced optimizations like tree-shaking to produce exceptionally small and efficient bundles. Rollup's current stable version is `4.60.2`, with frequent minor and patch releases (often weekly or bi-weekly) addressing bugs and adding features, while major versions introduce significant changes. Unlike bundlers focused on web applications, Rollup excels at bundling libraries and frameworks, offering a lean core with a powerful, flexible plugin API to handle various build scenarios, including CommonJS, AMD, UMD, and ES module outputs for different environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically use Rollup with its JavaScript API to bundle a project, including common plugins for module resolution and CommonJS conversion, and outputs to an ES module format with sourcemaps.

import { rollup } from 'rollup';
import type { InputOptions, OutputOptions, RollupBuild } from 'rollup';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';

async function buildBundle() {
  // Define input options for your Rollup build
  const inputOptions: InputOptions = {
    input: 'src/main.js', // Your application's entry point
    plugins: [
      resolve(), // Locates modules using Node.js resolution algorithm
      commonjs(), // Converts CommonJS modules to ES6, so they can be bundled by Rollup
      // Add other plugins like @rollup/plugin-typescript, @rollup/plugin-babel here
    ],
  };

  // Define output options for the generated bundle
  const outputOptions: OutputOptions = {
    file: 'dist/bundle.js',
    format: 'es', // Output format: 'es' (ES Modules), 'cjs' (CommonJS), 'umd', 'iife', etc.
    sourcemap: true, // Generate sourcemaps for debugging
    name: 'myLibrary', // Required for IIFE/UMD formats
  };

  let bundle: RollupBuild | undefined;
  try {
    // 1. Call rollup to create a bundle
    bundle = await rollup(inputOptions);

    // 2. Generate and write the output file(s)
    await bundle.write(outputOptions);

    console.log('Rollup build completed successfully!');
  } catch (error) {
    console.error('Rollup build failed:', error);
    process.exit(1);
  } finally {
    // 3. Close the bundle to release resources (e.g., file watchers)
    if (bundle) {
      await bundle.close();
    }
  }
}

// Example entry file (src/main.js):
// export const greet = (name) => `Hello, ${name}!`;
// console.log(greet('World'));

buildBundle();

view raw JSON →