DEV Community

Arhan Khan
Arhan Khan

Posted on

Rollup for Beginners: Bundle Your JavaScript Without the Bloat

If you have ever shipped a JavaScript library and wondered why the bundle was so big, Rollup is the tool that answers that question. Rollup is a module bundler for JavaScript, and it has one clear job: take your many small files and turn them into one clean, small output file.

What Rollup actually does

You write your code in separate modules — one file for helpers, one for the main logic, one for the config. Rollup follows your import and export statements, builds a graph of what depends on what, and writes a single bundle that includes only the code you actually use. Code you import but never call is dropped. That technique is called tree-shaking, and Rollup was the first bundler to do it well.

// math.js
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }

// main.js
import { add } from './math.js';
console.log(add(2, 3));
Enter fullscreen mode Exit fullscreen mode

Bundle this with Rollup and subtract disappears from the output, because nothing uses it. The result is smaller, and smaller means faster for your users.

How to start

Install it as a development dependency:

npm install --save-dev rollup
Enter fullscreen mode Exit fullscreen mode

Create a config file, rollup.config.js:

export default {
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'esm'
  }
};
Enter fullscreen mode Exit fullscreen mode

Then run:

npx rollup -c
Enter fullscreen mode Exit fullscreen mode

That is the whole workflow. When you need more — TypeScript, CSS, or minification — you add plugins, one at a time, instead of getting a giant setup on day one.

When to use Rollup, and when not to

Rollup shines for libraries and packages. If you are publishing something to npm, Rollup gives you the smallest, cleanest output of any bundler. Vite uses Rollup under the hood for production builds, which is why Vite apps ship small bundles.

For a big app with lots of assets, images, and hot reloading, a tool like Vite or webpack may fit better out of the box. Rollup is not worse — it is simply focused. It does one thing, bundling, and does it very well.

The one thing to remember

Write your code in small modules with clear export statements. Rollup can only tree-shake what it can see, so sloppy exports mean bigger bundles. Clean modules in, small bundle out.

Top comments (0)