Rollup Plugins & Externals
Rollup's core does very little on purpose: it bundles ES modules from relative paths. Everything else (finding packages in node_modules, converting CommonJS, compiling TypeScript, minifying) is a plugin. Rollup's plugin interface is so well designed that Vite adopted it wholesale, so what you learn here also applies to Vite plugins.
Rollup alone doesn't read node_modules
mkdir -p bare/src && cd bare
npm init -y > /dev/null && npm pkg set type=module
npm install ms@2.1.3 > /dev/null && npm install -D rollup@4.65.0 > /dev/null 2>&1
echo 'import ms from "ms"; console.log(ms(2000));' > src/index.js
npx rollup src/index.js --file dist/out.js --format es 2>&1 | grep -v created
head -1 dist/out.js
src/index.js → dist/out.js...
(!) Unresolved dependencies
https://rollupjs.org/troubleshooting/#warning-treating-module-as-external-dependency
ms (imported by "src/index.js")
import ms from 'ms';
Rollup couldn't resolve ms (a bare specifier), warned, and treated it as external. For a library that's often exactly what you want (declare it external to silence the warning); for an application bundle you need @rollup/plugin-node-resolve to find packages and @rollup/plugin-commonjs to convert CommonJS packages like ms to ES modules.
The common official plugins (not installed in this course's registry, so shown as configuration only):
// rollup.config.js for an application or a library that inlines some deps
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import json from '@rollup/plugin-json';
import terser from '@rollup/plugin-terser';
export default {
input: 'src/index.ts',
output: { dir: 'dist', format: 'es', sourcemap: true },
plugins: [nodeResolve(), commonjs(), json(), typescript(), terser()],
};Order matters: resolution and conversion first, compilation next, minification last.
external as a function
For libraries, a function is more robust than a list: treat every bare import as external, so new dependencies never get inlined by accident:
import pkg from './package.json' with { type: 'json' };
const deps = [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.peerDependencies ?? {})];
export default {
input: 'src/index.js',
// 'react' and 'react/jsx-runtime' both external; './utils.js' bundled
external: (id) => deps.some((d) => id === d || id.startsWith(d + '/')) || id.startsWith('node:'),
output: [{ file: 'dist/index.js', format: 'es' }],
};Writing plugins
A Rollup plugin is an object with a name and hooks. The build hooks run while the graph is built; the output hooks run once per output format:
| Hook | Phase | Use |
|---|---|---|
resolveId(source, importer) |
build | redirect imports, create virtual modules |
load(id) |
build | supply a module's code |
transform(code, id) |
build | change a module's code (compile, replace) |
buildEnd() |
build | after the graph is complete |
renderChunk(code, chunk) |
output | change a finished chunk (banners, minify) |
generateBundle(options, bundle) |
output | inspect or add files (this.emitFile) |
Here are three small plugins in one config: a virtual module, a build-time replacement, and a size report emitted as an extra file:
mkdir -p plug/src && cd plug
npm init -y > /dev/null && npm pkg set type=module version=2.4.0
npm install -D rollup@4.65.0 > /dev/null 2>&1
cat > src/index.js <<'JS'
import { features } from 'virtual:features';
export const banner = () => `app v__VERSION__ with ${features.join(', ')}`;
export const unused = () => 'tree-shaken away';
JS
cat > rollup.config.js <<'JS'
import { readFileSync } from 'node:fs';
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
const virtualFeatures = () => ({
name: 'virtual-features',
resolveId(source) { return source === 'virtual:features' ? '\0virtual:features' : null; },
load(id) { return id === '\0virtual:features' ? 'export const features = ["search", "export"];' : null; },
});
const version = () => ({
name: 'version',
transform(code, id) {
if (!code.includes('__VERSION__')) return null;
return { code: code.replaceAll('__VERSION__', pkg.version), map: null };
},
});
const sizeReport = () => ({
name: 'size-report',
generateBundle(options, bundle) {
const lines = Object.values(bundle).filter((f) => f.type === 'chunk')
.map((c) => `${c.fileName}: ${c.code.length} bytes, modules: ${Object.keys(c.modules).map((m) => m.replace(process.cwd() + '/', '').replace('\0', '\\0')).join(', ')}`);
this.emitFile({ type: 'asset', fileName: 'size-report.txt', source: lines.join('\n') + '\n' });
},
});
export default {
input: 'src/index.js',
plugins: [virtualFeatures(), version(), sizeReport()],
output: [{ dir: 'dist/es', format: 'es' }, { dir: 'dist/cjs', format: 'cjs', entryFileNames: '[name].cjs' }],
};
JS
npx rollup -c --silent
find dist -type f | sort
cat dist/es/index.js
cat dist/es/size-report.txt dist/cjs/size-report.txtdist/cjs/index.cjs
dist/cjs/size-report.txt
dist/es/index.js
dist/es/size-report.txt
const features = ["search", "export"];
const banner = () => `app v2.4.0 with ${features.join(', ')}`;
const unused = () => 'tree-shaken away';
export { banner, unused };
index.js: 172 bytes, modules: \0virtual:features, src/index.js
index.cjs: 210 bytes, modules: \0virtual:features, src/index.js
resolveIdreturned an id starting with\0, Rollup's convention for virtual modules (other plugins skip them, and they never touch the disk).transformran once per module during the build;generateBundleran once per output, so each format got its own report.unusedsurvived. It's an export of the entry module, and a library's entry exports are its public API, so Rollup never removes them; tree shaking only drops code that no kept export reaches.
Plugins that only use these standard hooks also work in Vite, which runs Rollup-style plugins in both its dev server and its build.
Test yourself
What does Rollup do with import ms from 'ms' when no resolve plugin is configured?
- Bundles node_modules/ms automatically
- Warns about an unresolved dependency and treats it as external
- Fails the build
- Downloads ms
Which hook would you use to replace a placeholder in source files?
- resolveId
- transform
- generateBundle
- buildEnd
Why do virtual module ids start with \0?
- It's required by Node
- By convention it tells other plugins this id is virtual and not a file path
- It makes the module external
- It speeds up hashing