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">