Frontend Development 23 min read

Master Rollup Plugins: From Basics to Advanced Hook Techniques

This article provides a comprehensive guide to Rollup plugins, explaining why plugins are needed, detailing hook types and their execution timing, showing how to create simple plugins with example code, and exploring internal mechanisms such as PluginDriver, hook loading, and caching.

WeDoctor Frontend Technology
WeDoctor Frontend Technology
WeDoctor Frontend Technology
Master Rollup Plugins: From Basics to Advanced Hook Techniques

Why Rollup Needs Plugins

Rollup builds a simple bundle by linking an entry file and its modules, but complex bundles require flexibility such as loading npm modules, Babel compilation, or JSON handling. Plugins allow developers to modify Rollup's behavior at key points, similar to Webpack plugins but without separating loaders and plugins.

Understanding Rollup Plugins

Official Definition

A Rollup plugin is an object with one or more properties, build hooks, and output generation hooks that follows Rollup's conventions. It should be distributed as a package exporting a function that accepts plugin‑specific options and returns the object. Plugins let you customize Rollup, for example by compiling code before bundling or locating third‑party modules in node_modules .

In practice a plugin is a plain function returning an object containing fields like

name

and hook functions for the build and output phases.

Conventions

Plugin name should start with

rollup-plugin-

.

Include

rollup-plugin

keyword in

package.json

.

Support testing, preferably with

mocha

or

ava

.

Prefer asynchronous methods.

Document the plugin in English.

Provide correct source maps.

For virtual modules, prefix the module name with

\0

to prevent other plugins from processing it.

Write a Rollup Plugin in Minutes

To stay motivated, start with a small example. You can inspect existing plugins—many are under 100 lines. For instance,

@rollup/plugin-image

is less than 50 lines, and

@rollup/plugin-json

is even shorter.

Simple Example

<code>export default function myExample() {
  return {
    name: 'my-example',
    resolveId(source) {
      if (source === 'virtual-module') {
        return source; // Rollup should not query other plugins or the file system
      }
      return null;
    },
    load(id) {
      if (id === 'virtual-module') {
        return 'export default "This is virtual!"';
      }
      return null;
    }
  };
}

// rollup.config.js
import myExample from './rollup-plugin-my-example.js';
export default {
  input: 'virtual-module',
  plugins: [myExample()],
  output: [{ file: 'bundle.js', format: 'es' }]
};
</code>

Now create a custom plugin that replaces a keyword in the bundle:

<code>export default function bundleReplace() {
  return {
    name: 'bundle-replace',
    transformBundle(bundle) {
      return bundle
        .replace('key_word', 'replace_word')
        .replace(/正则/, '替换内容');
    }
  };
}

// rollup.config.js
import bundleReplace from './rollup-plugin-bundle-replace.js';
export default {
  input: 'src/main.js',
  plugins: [bundleReplace()],
  output: [{ file: 'bundle.js', format: 'es' }]
};
</code>

Implementation of Rollup Plugin Functions

Rollup's plugin system revolves around nine hook‑loading functions in

PluginDriver.ts

, each handling different execution strategies such as

hookFirst

,

hookFirstSync

,

hookParallel

,

hookReduceArg0

,

hookSeq

, and their synchronous counterparts.

Hook Execution Timing

Hooks are grouped into three categories:

Build hooks executed during

rollup.rollup

(e.g.,

options

,

buildStart

,

buildEnd

).

Output generation hooks executed during

bundle.generate

or

bundle.write

(e.g.,

outputOptions

,

generateBundle

,

writeBundle

).

Watch hooks triggered in watch mode (e.g.,

watchChange

,

closeWatcher

).

Running Hooks

The core function

runHook

validates the hook, applies the plugin context, and either executes the function or returns a value if the hook is allowed to produce one. Errors are wrapped with

throwPluginError

.

Plugin Context

Rollup injects a context object into each hook, exposing utilities such as

addWatchFile

,

emitFile

,

getModuleInfo

,

resolve

, and a

cache

instance for plugin‑level caching.

Plugin Cache

Cache objects are created via closure in

createPluginCache

, providing

has

,

get

,

set

, and

delete

methods. The cache is attached to the plugin context, enabling plugins to store and reuse computation results across builds.

Summary

Rollup plugins are simple functions returning objects with hook methods. Understanding the nine hook‑loading functions, their execution timing, and the provided context allows developers to create powerful, efficient plugins and leverage built‑in caching for faster builds.

frontendplugin developmentRollupbuild hooksJavaScript bundler
WeDoctor Frontend Technology
Written by

WeDoctor Frontend Technology

Official WeDoctor Group frontend public account, sharing original tech articles, events, job postings, and occasional daily updates from our tech team.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.