0
# File Processing
1
2
File filtering, caching, and transformation system for handling TypeScript source files.
3
4
## Capabilities
5
6
### File Filtering
7
8
Configure which files are included or excluded from TypeScript compilation.
9
10
```typescript { .api }
11
interface FilterOptions {
12
/** File patterns to include for compilation */
13
include: string | string[];
14
15
/** File patterns to exclude from compilation */
16
exclude: string | string[];
17
18
/** Current working directory for pattern resolution */
19
cwd: string;
20
}
21
22
/**
23
* Create file filter function based on include/exclude patterns
24
* @param context - Rollup context for logging
25
* @param pluginOptions - Plugin configuration
26
* @param parsedConfig - Parsed TypeScript configuration
27
* @returns Filter function for file paths
28
*/
29
function createFilter(
30
context: RollupContext,
31
pluginOptions: IOptions,
32
parsedConfig: tsTypes.ParsedCommandLine
33
): (id: string) => boolean;
34
```
35
36
**Default Filter Patterns:**
37
38
```typescript { .api }
39
const defaultPatterns = {
40
include: [
41
"*.ts+(|x)", // .ts and .tsx files in root
42
"**/*.ts+(|x)", // .ts and .tsx files in subdirectories
43
"**/*.cts", // CommonJS TypeScript files
44
"**/*.mts" // ES Module TypeScript files
45
],
46
exclude: [
47
"*.d.ts", // Type declaration files in root
48
"**/*.d.ts", // Type declaration files in subdirectories
49
"**/*.d.cts", // CommonJS declaration files
50
"**/*.d.mts" // ES Module declaration files
51
]
52
};
53
```
54
55
**Filter Usage Examples:**
56
57
```javascript
58
// Custom file patterns
59
typescript({
60
include: ['src/**/*.ts', 'lib/**/*.tsx'],
61
exclude: ['**/*.test.ts', '**/*.spec.ts', 'node_modules/**']
62
})
63
64
// Include JavaScript files (requires allowJs in tsconfig)
65
typescript({
66
include: [
67
'*.ts+(|x)', '**/*.ts+(|x)', // TypeScript files
68
'*.js+(|x)', '**/*.js+(|x)' // JavaScript files
69
],
70
exclude: ['**/node_modules/**/*'] // Exclude node_modules for performance
71
})
72
```
73
74
### Caching System
75
76
Intelligent caching system for improved build performance across builds.
77
78
```typescript { .api }
79
/**
80
* TypeScript compilation cache
81
*/
82
class TsCache {
83
/**
84
* Create cache instance
85
* @param noCache - Disable caching entirely
86
* @param runClean - Clean existing cache on startup
87
* @param objectHashIgnoreUnknownHack - Ignore unknown objects in cache keys
88
* @param host - Language service host
89
* @param cacheRoot - Cache directory path
90
* @param options - Compiler options
91
* @param rollupOptions - Rollup configuration
92
* @param rootFileNames - Root files for compilation
93
* @param context - Rollup context
94
*/
95
constructor(
96
noCache: boolean,
97
runClean: boolean,
98
objectHashIgnoreUnknownHack: boolean,
99
host: LanguageServiceHost,
100
cacheRoot: string,
101
options: tsTypes.CompilerOptions,
102
rollupOptions: InputOptions,
103
rootFileNames: string[],
104
context: RollupContext
105
);
106
107
/** Get compiled output from cache or compile if needed */
108
getCompiled(
109
id: string,
110
snapshot: tsTypes.IScriptSnapshot,
111
getOutput: () => ICode
112
): ICode | undefined;
113
114
/** Get syntactic diagnostics from cache */
115
getSyntacticDiagnostics(
116
id: string,
117
snapshot: tsTypes.IScriptSnapshot,
118
getDiagnostics: () => readonly tsTypes.Diagnostic[]
119
): readonly tsTypes.Diagnostic[];
120
121
/** Get semantic diagnostics from cache */
122
getSemanticDiagnostics(
123
id: string,
124
snapshot: tsTypes.IScriptSnapshot,
125
getDiagnostics: () => readonly tsTypes.Diagnostic[]
126
): readonly tsTypes.Diagnostic[];
127
128
/** Set file dependency relationship */
129
setDependency(importee: string, importer: string): void;
130
131
/** Walk dependency tree and execute callback */
132
walkTree(callback: (id: string) => void): void;
133
134
/** Finalize cache operations */
135
done(): void;
136
}
137
```
138
139
**Cache Configuration:**
140
141
```javascript
142
// Custom cache settings
143
typescript({
144
clean: false, // Use existing cache (default)
145
cacheRoot: './build-cache', // Custom cache directory
146
147
// For cache debugging
148
objectHashIgnoreUnknownHack: false, // Strict cache key generation
149
verbosity: 3 // Log cache operations
150
})
151
152
// Development mode - fresh builds
153
typescript({
154
clean: true, // Always clean cache
155
verbosity: 2 // Show cache operations
156
})
157
158
// Production mode - optimized caching
159
typescript({
160
clean: false, // Preserve cache
161
cacheRoot: undefined, // Use default location
162
verbosity: 0 // Minimal logging
163
})
164
```
165
166
### Build Lifecycle Management
167
168
Integration with Rollup's build lifecycle for proper initialization and cleanup.
169
170
```typescript { .api }
171
/**
172
* Build lifecycle hooks
173
*/
174
interface BuildLifecycle {
175
/** Initialize plugin state and TypeScript service */
176
buildStart(): void;
177
178
/** Handle file changes in watch mode */
179
watchChange(id: string): void;
180
181
/** Finalize build and report diagnostics */
182
buildEnd(err?: Error): void;
183
184
/** Generate declaration files and assets */
185
generateBundle(options: OutputOptions, bundle: OutputBundle): void;
186
}
187
```
188
189
### File Transformation Pipeline
190
191
Core transformation logic for converting TypeScript to JavaScript.
192
193
```typescript { .api }
194
/**
195
* Transform TypeScript file to JavaScript
196
* @param code - Source TypeScript code
197
* @param id - File identifier/path
198
* @returns Transformed result with source maps
199
*/
200
interface TransformResult {
201
/** Generated JavaScript code */
202
code: string;
203
204
/** Source map for debugging */
205
map?: SourceMap;
206
}
207
208
/**
209
* Source map callback for custom processing
210
*/
211
type SourceMapCallback = (id: string, map: string) => void;
212
```
213
214
**Transform Process:**
215
216
1. **File Filtering**: Check if file should be processed
217
2. **Snapshot Creation**: Create TypeScript source snapshot
218
3. **Cache Lookup**: Check for cached compilation result
219
4. **Compilation**: Compile TypeScript to JavaScript if not cached
220
5. **Diagnostics**: Collect and report type errors
221
6. **Declaration Generation**: Generate .d.ts files if enabled
222
7. **Reference Tracking**: Track file dependencies for watch mode
223
224
```javascript
225
// Custom transformation handling
226
typescript({
227
sourceMapCallback: (id, map) => {
228
// Custom source map processing
229
console.log(`Generated source map for ${id}`);
230
// Could save to custom location, post-process, etc.
231
}
232
})
233
```
234
235
### Watch Mode Support
236
237
Enhanced watch mode integration for development workflows.
238
239
```typescript { .api }
240
/**
241
* Watch mode capabilities
242
*/
243
interface WatchMode {
244
/** Detect watch mode from environment */
245
watchMode: boolean;
246
247
/** Add files to Rollup's watch list */
248
addWatchFile(id: string): void;
249
250
/** Handle type-only imports that Rollup can't see */
251
handleTypeOnlyImports: boolean;
252
253
/** Support for Rollup 2.60.0+ this.load API */
254
supportsThisLoad: boolean;
255
}
256
```
257
258
**Watch Mode Features:**
259
260
- Automatic tsconfig.json watching
261
- Type-only import handling
262
- Incremental type checking
263
- Cache preservation between builds
264
- File dependency tracking
265
266
```javascript
267
// Watch mode configuration
268
typescript({
269
// These options are automatically optimized for watch mode:
270
clean: false, // Preserve cache between builds
271
check: true, // Enable incremental type checking
272
273
verbosity: 1, // Show warnings during development
274
abortOnError: false // Continue despite type errors
275
})
276
```
277
278
### Error Recovery and Reporting
279
280
Comprehensive error handling for build failures and type errors.
281
282
```typescript { .api }
283
/**
284
* Error handling configuration
285
*/
286
interface ErrorHandling {
287
/** Stop build on first error vs continue */
288
abortOnError: boolean;
289
290
/** Enable/disable type checking entirely */
291
check: boolean;
292
293
/** Control diagnostic verbosity */
294
verbosity: VerbosityLevel;
295
}
296
297
/**
298
* Error recovery strategies
299
*/
300
interface RecoveryStrategies {
301
/** Skip emit for files with errors */
302
emitSkipped: boolean;
303
304
/** Continue processing other files */
305
continueOnError: boolean;
306
307
/** Collect all diagnostics before reporting */
308
batchDiagnostics: boolean;
309
}
310
```
311
312
**Error Handling Examples:**
313
314
```javascript
315
// Strict mode - stop on any error
316
typescript({
317
abortOnError: true,
318
check: true,
319
verbosity: 1
320
})
321
322
// Lenient mode - collect all errors
323
typescript({
324
abortOnError: false, // Don't stop build
325
check: true, // Still check types
326
verbosity: 2 // Show detailed info
327
})
328
329
// Fast mode - skip type checking
330
typescript({
331
check: false, // Transpile only
332
abortOnError: true, // Stop on syntax errors only
333
verbosity: 0 // Minimal output
334
})
335
```