Rollup is a modern JavaScript module bundler designed with a primary focus on creating optimized libraries and applications. Its core strength lies in its ability to produce clean, efficient code by eliminating unused parts through a process called tree-shaking. This makes it an excellent choice for developers building SDKs, libraries, or any project where code size and performance are critical.
Rollup vs. Webpack: A Conceptual Overview
While both Webpack and Rollup are module bundlers, they serve different primary purposes. Webpack is a comprehennsive tool that excels at building complex, multi-asset applications. It handles not just JavaScript, but also CSS, images, and other resources, providing a rich ecosystem of loaders and plugins. In contrast, Rollup is more specialized. It prioritizes JavaScript and is exceptionally good at bundling ES modules, producing highly optimized output with minimal overhead. Projects like Vue, Vuex, and Vue Router leverage Rollup for this reason, whereas frameworks like Vue CLI and UI component libraries often use Webpack for its broader capabilities.
Setting Up a Basic Rollup Project
Let's walk through the steps to create a simple Rollup bundle.
1. Installation
First, install Rollup as a development dependency in your project:
npm install --save-dev rollup
2. Configuration
Create a configuration file named rollup.config.js in your project's root directory. This file defines how Rollup should process your code.
// rollup.config.js
export default {
// The entry point for your application/library
input: './src/main.js',
// The output configuration
output: {
// The destination file for the bundled code
file: './dist/bundle.min.js',
// The format of the output bundle
format: 'umd' // Universal Module Definition
}
};
3. Project Scripts
Add a build script to your package.json to execute Rollup using the configuration file.
// package.json
"scripts": {
"build": "rollup -c"
}
You can now run the build process with npm run build.
Demonstrating Tree-Shaking
Rollup's tree-shaking capability is a key feature. It analyzes your code and removes any unused exports, resulting in a smaller bundle. Consider the following example structure:
Source Code
src/math/calculateSum.js
// Exports a function to calculate the sum of an array
export const calculateSum = (numbers) => {
return numbers.reduce((total, current) => total + current, 0);
};
src/greetings/greetUser.js
// Exports two greeting functions
export const greetUser = (name) => {
return `Hello, ${name}!`;
};
export const farewellUser = (name) => {
return `Goodbye, ${name}.`;
};
src/main.js
// Imports only the functions that are actually used
import { calculateSum } from './math/calculateSum.js';
import greetUser from './greetings/greetUser.js';
const total = calculateSum([1, 2, 3, 4, 5]);
const message = greetUser('Alice');
console.log(total); // Outputs: 15
console.log(message); // Outputs: Hello, Alice!
When you build this project, Rollup will analyze the imports in main.js. It sees that farewellUser is never used, so it will not include it in the final bundle. The resulting bundle.min.js will only contain the code for calculateSum and greetUser.
Transpiling for Older Browsers with Babel
By default, Rollup outputs modern JavaScript. To ensure compatibility with older browsers like Internet Explorer, you can integrate Babel for transpilation.
1. Install Dependencies
npm install --save-dev @babel/core @babel/preset-env @babel/plugin-external-helpers rollup-plugin-babel
2. Babel Configuration
Create a .babelrc file in your project root to specify the Babel presets and plugins.
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
]
],
"plugins": ["@babel/plugin-external-helpers"]
}
3. Update Rollup Config
Modify your rollup.config.js to include the Babel plugin. This plugin will transpile your code during the bundling process.
// rollup.config.js
import babel from 'rollup-plugin-babel';
export default {
input: './src/main.js',
output: {
file: './dist/bundle.min.js',
format: 'umd'
},
plugins: [
babel({
exclude: 'node_modules/**' // Skip transpiling dependencies
})
]
};
With this setup, your ES6+ code (like arrow functions) will be converted to ES5-compatible syntax in the final bundle, ensuring broader browser support.
Minifying the Output
For production builds, you'll want to minify your code to reduce its size. The rollup-plugin-uglify plugin is perfect for this.
1. Install the Plugin
npm install --save-dev rollup-plugin-uglify
2. Update Rollup Config
Add the Uglify plugin to your configuration. It's often placed last in the plugins array to ensure other transformations happen first.
// rollup.config.js
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
export default {
input: './src/main.js',
output: {
file: './dist/bundle.min.js',
format: 'umd'
},
plugins: [
babel({
exclude: 'node_modules/**'
}),
// Minify the final bundle
uglify()
]
};
Now, when you run your build script, the output will be both transpiled for compatibility and minified for optimal performance.