Getting Started with Rollup

Offical Document:
https://rollupjs.org/introduction/

Introduction to 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 uses the standardized ES module format for code, instead of previous custom solutions like CommonJS and AMD. Rollup allows you to write your code using ES modules, and then efficiently bundle it for production.
Unlike webpack, which is designed primarily for applications, Rollup excels at bundling libraries and focuses on producing smaller, more efficient bundles by leveraging ES modules.

Creating Your First Bundle

1
npm install rollup --global

Create a simple project:

1
2
mkdir -p my-rollup-project/src
cd my-rollup-project

src/main.js

1
2
3
4
import foo from './foo.js';
export default function () {
console.log(foo);
}

src/foo.js

1
export default 'hello world!';
1
rollup src/main.js -f cjs

save the bundle

1
rollup src/main.js -o bundle.js -f cjs

Using Config Files

Instead of using command-line arguments, you can create a configuration file:

rollup.config.mjs

1
2
3
4
5
6
7
export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
}
};
1
rollup -c

Installing Rollup locally

For project-specific installations:

1
pnpm i rollup --save-dev

Update your package.json:

1
2
3
4
5
{
"scripts": {
"build": "rollup --config"
}
}

Using pluings

Install a plugin to handle JSON files:

1
pnpm install --save-dev @rollup/plugin-json

Update src/main.js

1
2
3
4
5
6
// src/main.js
import { version } from '../package.json';

export default function () {
console.log('version ' + version);
}

rollup.config.mjs

1
2
3
4
5
6
7
8
9
10
11
// rollup.config.mjs
import json from '@rollup/plugin-json';

export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
plugins: [json()]
};

Comprehensive Rollup Configuration

Rollup’s configuration can be quite extensive.
Below is a comprehensive guide to the major configuration options.

Basic Configuration Structure

A comprehensive Rollup config might look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
export default {
// Core input options
input,
external,
plugins,

// Advanced input options
onwarn,
cache,
perf,

// Output options (can be an array for multiple outputs)
output: {
// Core output options
file,
format,
dir,
name,
globals,

// Advanced output options
paths,
banner,
footer,
intro,
outro,
sourcemap,
sourcemapFile,
interop,
exports,

// Danger zone
amd,
esModule,
compact,
indent,
strict,
freeze,
namespaceToStringTag,

// Experimental
experimentalDeepDynamicChunkOptimization,
chunkFileNames,
entryFileNames,
assetFileNames
}
};

Key Configuration Options

Input Options

  1. input (String | String[] | { [entryName: string]: string }): The entry point(s) for your bundle.

  2. external (Array | Function | RegExp): IDs of modules that should remain external to the bundle.

  3. plugins (Array): An array of plugin objects to be applied to the bundle.

  4. cache (Object): Previous bundle. Used to speed up incremental builds.

Output Options

  1. file (String): The file to write to. Cannot be used with dir.

  2. format (String): The format of the generated bundle. Options:

    • amd - Asynchronous Module Definition
    • cjs - CommonJS
    • es or esm - ES modules
    • iife - Immediately-invoked Function Expression
    • umd - Universal Module Definition
    • system - SystemJS
  3. dir (String): Directory for chunk files. Used for code-splitting or multiple entry points.

  4. name (String): Variable name for IIFE/UMD bundles.

  5. globals (Object): Map of external imports to global variables for UMD/IIFE bundles.

  6. sourcemap (Boolean | ‘inline’ | ‘hidden’): Controls source map generation.

  7. banner/footer (String): Code to prepend/append to the bundle.

Advanced Configuration

Code Splitting

Rollup supports code splitting by specifying multiple entry points or using dynamic imports:

1
2
3
4
5
6
7
export default {
input: ['src/main.js', 'src/another-entry.js'],
output: {
dir: 'dist',
format: 'es'
}
};

Tree Shaking

One of Rollup’s strengths is tree shaking - eliminating unused code.
This works automatically when using ES modules, but can be affected by certain plugins and configurations.

Preserving Modules

1
2
3
4
5
6
7
8
export default {
input: 'src/index.js',
output: {
dir: 'dist',
format: 'es',
preserveModules: true // Keep the module structure
}
};

Rollup’s functionality can be extended with plugins:

  1. @rollup/plugin-node-resolve: Locates modules using the Node resolution algorithm.
1
2
3
4
5
6
7
8
9
import resolve from '@rollup/plugin-node-resolve';

export default {
plugins: [
resolve({
browser: true // For browser compatibility
})
]
};
  1. @rollup/plugin-commonjs: Converts CommonJS modules to ES modules.
1
2
3
4
5
6
7
import commonjs from '@rollup/plugin-commonjs';

export default {
plugins: [
commonjs()
]
};
  1. @rollup/plugin-babel: Integrates Babel with Rollup.
1
2
3
4
5
6
7
8
9
10
import babel from '@rollup/plugin-babel';

export default {
plugins: [
babel({
babelHelpers: 'bundled',
exclude: 'node_modules/**'
})
]
};
  1. @rollup/plugin-terser: Minifies the bundle using Terser.
1
2
3
4
5
6
7
import terser from '@rollup/plugin-terser';

export default {
plugins: [
terser()
]
};
  1. @rollup/plugin-replace: Replace strings in the code with other values.
1
2
3
4
5
6
7
8
9
10
import replace from '@rollup/plugin-replace';

export default {
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
preventAssignment: true
})
]
};

Babel and Its Common Plugins

Introduction to Babel

Babel is a JavaScript compiler that transforms modern JavaScript code into backward compatible versions for older browsers or environments. It’s commonly used with Rollup to ensure wide browser compatibility.

Setting Up Babel with Rollup

1
pnpm install --save-dev @babel/core @babel/preset-env @rollup/plugin-babel

Configure Babel with Rollup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// rollup.config.mjs
import babel from '@rollup/plugin-babel';

export default {
input: 'src/main.js',
output: {
file: 'bundle.js',
format: 'cjs'
},
plugins: [
babel({
babelHelpers: 'bundled',
exclude: 'node_modules/**'
})
]
};

Create a Babel configuration file:

1
2
3
4
5
6
7
8
// babel.config.json
{
"presets": [
["@babel/preset-env", {
"targets": "> 0.25%, not dead"
}]
]
}

Common Babel Presets

Presets are collections of plugins used to support particular language features.

  1. @babel/preset-env:
    Transforms ES2015+ code to be compatible with specified environments.
    • Purpose: Automatically determines plugins needed based on browser targets.
    • Features: Transforms new JavaScript syntax, doesn’t transform new JavaScript APIs.
1
2
3
4
5
6
7
8
9
10
11
12
{
"presets": [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions", "not dead"],
"node": "current"
},
"useBuiltIns": "usage", // Adds specific imports for polyfills
"corejs": 3 // Version of core-js
}]
]
}
  1. @babel/preset-react:
    Transforms JSX syntax for React applications.
    • Purpose: Provides plugins for React development.
    • Features: Transforms JSX into React.createElement() calls, supports React development mode.
1
2
3
4
5
6
7
8
{
"presets": [
["@babel/preset-react", {
"runtime": "automatic", // Uses React 17's new JSX transform
"development": process.env.NODE_ENV === "development"
}]
]
}
  1. @babel/preset-typescript:
    Transforms TypeScript code to JavaScript.
    • Purpose: Strips TypeScript type annotations.
    • Features: Allows using TypeScript without requiring the TypeScript compiler.
1
2
3
4
5
6
7
8
{
"presets": [
["@babel/preset-typescript", {
"isTSX": true, // Support for TSX files
"allExtensions": true
}]
]
}

Common Babel Plugins

Beyond presets, individual plugins can add specific functionality:

  1. @babel/plugin-transform-runtime: Externalizes references to helpers and builtins.
    • Purpose: Avoids duplication of helper functions in every file.
    • Use case: When building libraries or larger applications.
1
2
3
4
5
6
7
{
"plugins": [
["@babel/plugin-transform-runtime", {
"corejs": 3
}]
]
}
  1. @babel/plugin-proposal-decorators: Enables decorator syntax support.
    • Purpose: Transforms decorator syntax for classes and class properties.
    • Use case: When using libraries like MobX or TypeScript decorators.
1
2
3
4
5
6
7
{
"plugins": [
["@babel/plugin-proposal-decorators", {
"legacy": true
}]
]
}
  1. @babel/plugin-proposal-class-properties: Transforms static class properties.
    • Purpose: Enables class instance and static properties.
    • Use case: When using modern class syntax features.
1
2
3
4
5
{
"plugins": [
["@babel/plugin-proposal-class-properties"]
]
}
  1. @babel/plugin-proposal-object-rest-spread: Transforms rest and spread properties.
    • Purpose: Enables object rest/spread syntax.
    • Use case: When using modern object manipulation syntax.
1
2
3
4
5
{
"plugins": [
["@babel/plugin-proposal-object-rest-spread"]
]
}
  1. @babel/plugin-syntax-dynamic-import: Adds support for the dynamic import syntax.
    • Purpose: Enables parsing of import() syntax for code splitting.
    • Use case: When implementing code splitting in applications.
1
2
3
4
5
{
"plugins": [
["@babel/plugin-syntax-dynamic-import"]
]
}

Complete Example: Rollup with Babel and TypeScript

Here’s a comprehensive example combining Rollup, Babel, and TypeScript:

Install dependencies:

1
pnpm install --save-dev rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-babel @rollup/plugin-typescript @babel/core @babel/preset-env @babel/preset-typescript typescript

rollup.config.mjs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';

const production = !process.env.ROLLUP_WATCH;

export default {
input: 'src/main.ts',
output: [
{
file: 'dist/bundle.cjs.js',
format: 'cjs',
sourcemap: !production
},
{
file: 'dist/bundle.esm.js',
format: 'esm',
sourcemap: !production
},
{
file: 'dist/bundle.umd.js',
format: 'umd',
name: 'MyLibrary',
sourcemap: !production
}
],
plugins: [
typescript({
tsconfig: './tsconfig.json',
sourceMap: !production
}),
resolve({
browser: true
}),
commonjs(),
babel({
extensions: ['.js', '.ts'],
babelHelpers: 'bundled',
exclude: 'node_modules/**',
presets: [
['@babel/preset-env', {
targets: '> 0.25%, not dead'
}],
'@babel/preset-typescript'
]
}),
production && terser()
]
};

tsconfig.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"compilerOptions": {
"target": "es2018",
"module": "esnext",
"moduleResolution": "node",
"declaration": true,
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

Getting Started with Rollup
https://www.hardyhu.cn/2025/02/14/Getting-Started-with-Rollup/
Author
John Doe
Posted on
February 14, 2025
Licensed under