Rollup with TypeScript
In this page:
Core Concept
Rollup is a bundler focused on producing small, tree-shaken output — especially for libraries — and understands ES modules natively, pairing with @rollup/plugin-typescript to compile .ts source files during the bundle step.
Example: Core Concept
// rollup.config.js uses @rollup/plugin-typescript to compile .ts sources
console.log("Rollup focuses on small, tree-shaken output for libraries");
Basic Setup
A basic setup adds @rollup/plugin-typescript to the plugins array in rollup.config.js (or .mjs), pointing it at your tsconfig.json so Rollup compiles TypeScript using your project's existing compiler options.
Example: Basic Setup
// import typescript from "@rollup/plugin-typescript";
// export default { plugins: [typescript()] };
console.log("plugin-typescript compiles using your existing tsconfig.json");
Typed Example
Rollup can emit multiple typed output formats (ESM, CJS, UMD) from one typed source tree in a single config, useful when publishing a library that needs to support both modern bundlers and older CommonJS consumers.
Example: Typed Example
// output: [{ format: "esm" }, { format: "cjs" }, { format: "umd", name: "MyLib" }]
console.log("Rollup can emit multiple typed output formats from one source tree");
Project Usage
In a real project, Rollup's aggressive tree-shaking means only the typed exports actually imported by a consumer end up in their bundle, which is why it's the standard choice for publishing typed npm libraries.
Example: Project Usage
// Only imported, used exports end up in the consumer's final bundle
console.log("Aggressive tree-shaking makes Rollup common for npm libraries");
Best Practices
Emit .d.ts declaration files alongside your bundle (via tsc --emitDeclarationOnly or rollup-plugin-dts) so consumers of your published library get full type information, not just compiled JavaScript.
Example: Best Practices
// tsc --emitDeclarationOnly (or rollup-plugin-dts)
console.log("Emit .d.ts files alongside the bundle for library consumers");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: