← Back to TypeScript Course | Chapter 25: Build Tools | Lesson 3 of 6

Rollup with TypeScript

Rollup is a module bundler commonly used to build libraries. TypeScript can provide type checking while Rollup produces optimized JavaScript bundles.

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

typescript
// 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

typescript
// 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

typescript
// 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

typescript
// 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

typescript
// 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.