Introduction to Rollup
Rollup is a module bundler for JavaScript, designed to compile small pieces of code into something larger and more complex, such as a library or application. It offers a versatile and optimized approach to bundling JavaScript modules, providing developers with powerful tools to enhance their workflow. In this guide, we’ll introduce Rollup and delve into its useful API with code snippets, along with a practical app example that utilizes these APIs.
Getting Started
To start using Rollup, install it via npm:
npm install --global rollup
Basic Configuration
Create a configuration file named rollup.config.js
:
import { terser } from 'rollup-plugin-terser'; export default { input: 'src/main.js', output: { file: 'dist/bundle.js', format: 'cjs', }, plugins: [terser()] };
Useful API Examples
1. inputOptions
Defines Rollup’s input configuration:
const inputOptions = { input: 'src/input.js', plugins: [] };
2. outputOptions
Defines Rollup’s output configuration:
const outputOptions = { file: 'dist/output.js', format: 'iife', name: 'MyBundle' };
3. plugin-babel
Using Babel with Rollup:
import babel from '@rollup/plugin-babel'; export default { input: 'src/main.js', output: { file: 'bundle.js', format: 'cjs' }, plugins: [babel({ babelHelpers: 'bundled' })] };
4. dynamic-import-vars
Configuration for dynamic imports:
import dynamicImportVars from '@rollup/plugin-dynamic-import-vars'; export default { input: 'src/main.js', output: { dir: 'output', format: 'cjs' }, plugins: [dynamicImportVars()] };
App Example with APIs
Here is a simple app that demonstrates the use of Rollup APIs:
// src/main.js import { myFunction } from './module.js'; myFunction(); // src/module.js export function myFunction() { console.log('Hello from Rollup!'); } // rollup.config.js import babel from '@rollup/plugin-babel'; import { terser } from 'rollup-plugin-terser'; export default { input: 'src/main.js', output: { file: 'dist/bundle.js', format: 'iife', name: 'App' }, plugins: [ babel({ babelHelpers: 'bundled' }), terser() ] };