Unbuild for TypeScript: A Complete Guide with Examples
In the modern JavaScript and TypeScript ecosystem, project bundling is a critical task. Developers often face the complexity of configuring Webpack, Rollup, or esbuild. The unbuild library offers an elegant solution — a unified build system that combines best practices and tools into a single interface. It's not just another bundler; it's a streamlined wrapper around esbuild and Rollup that automatically determines the optimal build strategy for your project.
The primary goal of unbuild is to simplify the process of building TypeScript libraries. Instead of spending hours tweaking configuration files, developers get a ready-to-use solution out of the box. The library automatically generates CommonJS and ESM builds, creates type declarations (d.ts), optimizes bundles, and supports modern TypeScript features. This makes unbuild an ideal choice for npm package authors and open-source projects.
Unbuild is especially useful in these scenarios: creating monorepos, building libraries with tree-shaking support, publishing packages with TypeScript source files, and migrating from legacy bundlers. With built-in support for package.json exports and automatic entry point detection, the library lets you focus on writing code instead of configuring infrastructure.
Installation
To install unbuild, use npm (or alternatives like yarn or pnpm). Install it as a dev dependency:
npm install -D unbuild
Or with yarn:
yarn add -D unbuild
For pnpm:
pnpm add -D unbuild
After installation, add a build script to your package.json:
{
"scripts": {
"build": "unbuild",
"dev": "unbuild --watch"
}
}
Quick Start
Let's create a minimal working project. File structure:
my-library/
├── src/
│ └── index.ts
├── package.json
└── tsconfig.json
Contents of src/index.ts:
export function greet(name: string): string {
return `Hello, ${name}!`;
}
export const version = '1.0.0';
tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"declaration": true,
"outDir": "./dist"
},
"include": ["src"]
}
Now run the build:
npx unbuild
After execution, the dist folder will contain these files:
dist/index.mjs— ESM builddist/index.cjs— CommonJS builddist/index.d.ts— Type declarationsdist/index.d.mts— Declarations for ESM
Unbuild automatically creates both builds and generates TypeScript declarations. To configure exports in package.json, add:
{
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts"
}
}
}
Core Methods and Functions
1. defineBuildConfig(config)
Signature: defineBuildConfig(config: BuildConfig): BuildConfig
Description: The main function for creating a build configuration. It accepts a settings object and returns it with full type safety.