0
# Build System
1
2
Core build functionality for bundling TypeScript/JavaScript libraries with Rolldown. Provides high-performance bundling with TypeScript support, multiple output formats, and extensive configuration options.
3
4
## Capabilities
5
6
### Main Build Function
7
8
The primary entry point for building projects with tsdown.
9
10
```typescript { .api }
11
/**
12
* Build with tsdown. Main function for bundling libraries.
13
* @param userOptions - Build configuration options
14
*/
15
function build(userOptions?: Options): Promise<void>;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { build } from "tsdown";
22
23
// Simple build with defaults
24
await build();
25
26
// Build with specific entry and formats
27
await build({
28
entry: "src/index.ts",
29
format: ["esm", "cjs"],
30
dts: true
31
});
32
33
// Advanced configuration
34
await build({
35
entry: {
36
index: "src/index.ts",
37
cli: "src/cli.ts"
38
},
39
format: ["esm", "cjs"],
40
outDir: "dist",
41
sourcemap: true,
42
minify: true,
43
target: "node18",
44
external: ["lodash"],
45
dts: {
46
resolve: true
47
}
48
});
49
```
50
51
### Single Configuration Build
52
53
Internal build function for single configurations without watch mode.
54
55
```typescript { .api }
56
/**
57
* Build a single configuration, without watch and shortcuts features.
58
* Internal API, not for public use.
59
* @private
60
* @param config - Resolved options
61
* @param clean - Clean function to call before build
62
*/
63
function buildSingle(
64
config: ResolvedOptions,
65
clean: () => Promise<void>
66
): Promise<(() => Promise<void>) | undefined>;
67
```
68
69
### Core Options Interface
70
71
Main configuration interface for build options.
72
73
```typescript { .api }
74
interface Options {
75
// Input Options
76
/** Entry point(s) for the build. Defaults to 'src/index.ts' if it exists */
77
entry?: InputOption;
78
/** External dependencies to exclude from bundle */
79
external?: ExternalOption;
80
/** Dependencies to include in bundle (opposite of external) */
81
noExternal?:
82
| Arrayable<string | RegExp>
83
| ((id: string, importer: string | undefined) => boolean | null | undefined | void);
84
/** Skip bundling node_modules dependencies */
85
skipNodeModulesBundle?: boolean;
86
/** Path aliases for module resolution */
87
alias?: Record<string, string>;
88
/** TypeScript configuration file path */
89
tsconfig?: string | boolean;
90
/** Target runtime platform */
91
platform?: 'node' | 'neutral' | 'browser';
92
/** Compilation target environment(s) */
93
target?: string | string[] | false;
94
/** Compile-time environment variables */
95
env?: Record<string, any>;
96
/** Define compile-time constants */
97
define?: Record<string, string>;
98
/** Enable CJS and ESM shims */
99
shims?: boolean;
100
/** Enable tree-shaking */
101
treeshake?: boolean;
102
/** Module type overrides for file extensions */
103
loader?: ModuleTypes;
104
/** Node.js protocol handling */
105
nodeProtocol?: 'strip' | boolean;
106
/** Rolldown plugins */
107
plugins?: InputOptions['plugins'];
108
/** Custom input options function */
109
inputOptions?:
110
| InputOptions
111
| ((options: InputOptions, format: NormalizedFormat, context: { cjsDts: boolean }) => Awaitable<InputOptions | void | null>);
112
113
// Output Options
114
/** Output format(s) */
115
format?: Format | Format[];
116
/** Global variable name for IIFE/UMD formats */
117
globalName?: string;
118
/** Output directory */
119
outDir?: string;
120
/** Source map generation */
121
sourcemap?: Sourcemap;
122
/** Clean directories before build */
123
clean?: boolean | string[];
124
/** Minification options */
125
minify?: boolean | 'dce-only' | MinifyOptions;
126
/** Code to prepend to each chunk */
127
banner?: ChunkAddon;
128
/** Code to append to each chunk */
129
footer?: ChunkAddon;
130
/** Enable unbundle mode (mirrors input structure) */
131
unbundle?: boolean;
132
/** Use fixed extensions (.cjs/.mjs) */
133
fixedExtension?: boolean;
134
/** Custom output extensions */
135
outExtensions?: OutExtensionFactory;
136
/** Append hash to filenames */
137
hash?: boolean;
138
/** CommonJS default export handling */
139
cjsDefault?: boolean;
140
/** Custom output options function */
141
outputOptions?:
142
| OutputOptions
143
| ((options: OutputOptions, format: NormalizedFormat, context: { cjsDts: boolean }) => Awaitable<OutputOptions | void | null>);
144
145
// TypeScript Options
146
/** Generate TypeScript declaration files */
147
dts?: boolean | DtsOptions;
148
149
// Development Options
150
/** Working directory */
151
cwd?: string;
152
/** Project name for CLI output */
153
name?: string;
154
/** Log level */
155
logLevel?: LogLevel;
156
/** Fail build on warnings */
157
failOnWarn?: boolean;
158
/** Custom logger implementation */
159
customLogger?: Logger;
160
/** Configuration file path */
161
config?: boolean | string;
162
/** Reuse Vite/Vitest configuration */
163
fromVite?: boolean | 'vitest';
164
/** Enable watch mode */
165
watch?: boolean | Arrayable<string>;
166
/** Paths to ignore in watch mode */
167
ignoreWatch?: Arrayable<string | RegExp>;
168
/** Command or function to run on successful build */
169
onSuccess?:
170
| string
171
| ((config: ResolvedOptions, signal: AbortSignal) => void | Promise<void>);
172
173
// Quality Assurance Options
174
/** Enable unused dependency checking */
175
unused?: boolean | UnusedOptions;
176
/** Run publint after bundling */
177
publint?: boolean | PublintOptions;
178
/** Run Are The Types Wrong after bundling */
179
attw?: boolean | AttwOptions;
180
/** Enable size reporting */
181
report?: boolean | ReportOptions;
182
183
// Advanced Options
184
/** Generate package.json exports metadata */
185
exports?: boolean | ExportsOptions;
186
/** Copy files to output directory */
187
copy?: CopyOptions | CopyOptionsFn;
188
/** Build hooks for customization */
189
hooks?:
190
| Partial<TsdownHooks>
191
| ((hooks: Hookable<TsdownHooks>) => Awaitable<void>);
192
/** Workspace configuration for monorepos */
193
workspace?: Workspace | Arrayable<string> | true;
194
/** Filter workspace packages */
195
filter?: RegExp | string | string[];
196
}
197
```
198
199
### Resolved Options Interface
200
201
Internal resolved configuration after processing user options.
202
203
```typescript { .api }
204
interface ResolvedOptions {
205
// Core resolved properties
206
entry: InputOption;
207
format: NormalizedFormat[];
208
target?: string[];
209
outDir: string;
210
clean: string[];
211
dts: false | DtsOptions;
212
report: false | ReportOptions;
213
tsconfig: string | false;
214
pkg?: PackageJson;
215
exports: false | ExportsOptions;
216
nodeProtocol: 'strip' | boolean;
217
logger: Logger;
218
ignoreWatch: Array<string | RegExp>;
219
220
// All other Options properties (with some excluded/transformed)
221
plugins?: InputOptions['plugins'];
222
treeshake?: boolean;
223
platform?: 'node' | 'neutral' | 'browser';
224
sourcemap?: Sourcemap;
225
unused?: boolean | UnusedOptions;
226
watch?: boolean | Arrayable<string>;
227
shims?: boolean;
228
skipNodeModulesBundle?: boolean;
229
publint?: boolean | PublintOptions;
230
attw?: boolean | AttwOptions;
231
alias?: Record<string, string>;
232
cwd?: string;
233
env?: Record<string, any>;
234
copy?: CopyOptions | CopyOptionsFn;
235
hash?: boolean;
236
name?: string;
237
external?: ExternalOption;
238
noExternal?:
239
| Arrayable<string | RegExp>
240
| ((id: string, importer: string | undefined) => boolean | null | undefined | void);
241
unbundle?: boolean;
242
cjsDefault?: boolean;
243
}
244
```
245
246
### Input and Output Types
247
248
Type definitions for Rolldown integration.
249
250
```typescript { .api }
251
// Re-exported from rolldown
252
type InputOption = string | string[] | Record<string, string>;
253
type ExternalOption = (string | RegExp)[] | string | RegExp | ((id: string, importer?: string, isResolved?: boolean) => boolean | null | void);
254
type MinifyOptions = {
255
// Rolldown minification options
256
mangle?: boolean;
257
compress?: boolean;
258
};
259
260
// Chunk addon types
261
type ChunkAddon = string | ChunkAddonFunction | ChunkAddonObject;
262
type ChunkAddonFunction = (chunk: OutputChunk) => string | Promise<string>;
263
type ChunkAddonObject = {
264
[format in NormalizedFormat]?: string | ChunkAddonFunction;
265
};
266
267
// Output extension types
268
type OutExtensionFactory = OutExtensionObject | OutExtensionFunction;
269
type OutExtensionObject = Partial<Record<NormalizedFormat, string>>;
270
type OutExtensionFunction = (context: OutExtensionContext) => string | void;
271
interface OutExtensionContext {
272
format: NormalizedFormat;
273
options: ResolvedOptions;
274
}
275
```
276
277
## Build Process
278
279
The build process follows these key steps:
280
281
1. **Options Resolution**: User options are merged with defaults and validated
282
2. **Workspace Discovery**: If workspace mode is enabled, discover and process all packages
283
3. **Configuration Resolution**: Each configuration is resolved with proper paths and settings
284
4. **Clean Phase**: Output directories are cleaned if requested
285
5. **Build Phase**: Rolldown builds each format in parallel
286
6. **Post-processing**: Declaration files, copying, and quality checks are performed
287
7. **Reporting**: Size analysis and build summary are displayed
288
8. **Watch Mode**: If enabled, file watching and rebuild logic is activated
289
290
## Error Handling
291
292
The build system handles various error scenarios:
293
294
- **Configuration Errors**: Invalid options or missing files
295
- **Build Errors**: TypeScript errors, import resolution failures
296
- **Plugin Errors**: Plugin initialization or execution failures
297
- **File System Errors**: Permission issues, disk space problems
298
- **Watch Mode Errors**: File watching setup or rebuild failures
299
300
In watch mode, build errors are logged but don't terminate the process, allowing for continuous development.