Comprehensive Guide to Rollup A Powerful JavaScript Bundler

Introduction to Rollup

Rollup is a module bundler for JavaScript, allowing developers to write modular code and bundle it into small, easy-to-load scripts. It’s particularly well-suited for libraries and components, offering a slimmer, more optimized way to include dependencies.

Getting Started with Rollup

To get started with Rollup, you need to install it via npm:


  npm install --global rollup

Basic Usage

Create a simple input file named main.js:


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

Then create a module file named math.js:


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

To bundle these files into a single file, use the following command:


  rollup main.js --file bundle.js --format iife

Rollup Plugins

Plugins are a powerful way to extend the functionality of Rollup. For example, you can use the rollup-plugin-node-resolve to integrate with Node’s resolution algorithm:


  // rollup.config.js
  import resolve from 'rollup-plugin-node-resolve';

  export default {
    input: 'main.js',
    output: {
      file: 'bundle.js',
      format: 'iife'
    },
    plugins: [resolve()]
  };

Code Splitting

Rollup supports code splitting, allowing you to split your code into multiple chunks. Here’s an example:


  // main.js
  import('./math.js').then(({ add }) => {
    console.log(add(2, 3));
  });

Build this using:


  rollup main.js --format es --dir output

Tree Shaking

One of Rollup’s key features is tree shaking, which eliminates unused code. For example:


  // 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));

Rollup will automatically remove the subtract function from the final bundle because it is unused.

App Example

Here’s a complete example of a simple web application using Rollup:


  // index.html
  <   !DOCTYPE html>
  <   html lang="en">
  <     head>
  <       meta charset="UTF-8">
  <       meta name="viewport" content="width=device-width, initial-scale=1.0">
  <       title>Rollup App
  <       script defer src="bundle.js">
  <     /head>
  <     body>
  <       h1>Rollup Example
  <       div id="app">
< /body> < /html> // main.js import { add } from './math.js'; const result = add(5, 7); document.getElementById('app').innerText = `5 + 7 = ${result}`; // math.js export function add(a, b) { return a + b; } // rollup.config.js import resolve from 'rollup-plugin-node-resolve'; export default { input: 'main.js', output: { file: 'bundle.js', format: 'iife' }, plugins: [resolve()] };

This minimal web application demonstrates how to use Rollup to bundle a JavaScript file and include it in an HTML file.

Hash: 45fb8b4d67311a0905e8bcffe1f5a72eb4e62bcab4cc183d9b74609ae8ad968e

Leave a Reply

Your email address will not be published. Required fields are marked *