What is rollup?
Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It is optimized for bundling JavaScript files to use in a browser, and it is also capable of transforming code using plugins.
What are rollup's main functionalities?
Bundling Modules
Rollup can bundle multiple JavaScript modules into a single file. The above code demonstrates how to create a bundle from an entry point file 'src/main.js' and output it as an immediately-invoked function expression (IIFE) to 'bundle.js'.
import rollup from 'rollup';
async function build() {
const bundle = await rollup.rollup({
input: 'src/main.js'
});
await bundle.write({
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
});
}
build();
Tree-shaking
Rollup includes a feature called 'tree-shaking' which removes unused code from the final bundle. This helps in reducing the size of the bundle and improving load times.
import { rollup } from 'rollup';
rollup({
input: 'src/index.js',
treeshake: true // Tree-shaking is enabled by default
}).then(bundle => {
// Code to write the bundle
});
Plugin System
Rollup supports a wide range of plugins that can transform the code, add functionality, or integrate with other build tools. The code sample shows how to use the JSON plugin to import JSON files as modules.
import { rollup } from 'rollup';
import json from '@rollup/plugin-json';
rollup({
input: 'src/index.js',
plugins: [json()]
}).then(bundle => {
// Code to write the bundle
});
Other packages similar to rollup
webpack
Webpack is a powerful module bundler that can handle not only JavaScript but also assets like images, fonts, and stylesheets. It has a larger ecosystem and more configuration options compared to Rollup, making it more suitable for complex applications.
parcel
Parcel is a web application bundler that offers a zero-configuration experience. It is known for its fast build times and out-of-the-box support for various file types. Parcel is easier to set up than Rollup and Webpack but may offer less fine-grained control.
browserify
Browserify allows you to use `require('modules')` in the browser by bundling up all of your dependencies. It is one of the earlier bundlers and is focused on simplicity and ease of use, but it doesn't have built-in tree-shaking like Rollup.