0
# File Processing
1
2
Essential utilities for handling file paths, extensions, and filtering in Rollup plugin workflows. These functions provide cross-platform file handling and pattern-based filtering capabilities.
3
4
## Capabilities
5
6
### createFilter
7
8
Constructs a filter function to determine which modules should be processed by a plugin, using picomatch glob patterns.
9
10
```typescript { .api }
11
/**
12
* Creates a filter function for determining which modules should be processed
13
* @param include - Patterns for files to include (if omitted, all files included by default)
14
* @param exclude - Patterns for files to exclude (takes precedence over include)
15
* @param options - Configuration options for pattern resolution
16
* @returns Filter function that returns true if the file should be processed
17
*/
18
function createFilter(
19
include?: FilterPattern,
20
exclude?: FilterPattern,
21
options?: { resolve?: string | false | null }
22
): (id: string | unknown) => boolean;
23
24
type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
25
```
26
27
**Parameters:**
28
29
- `include` (FilterPattern, optional): Picomatch patterns for files to include. Can be a string, RegExp, or array of patterns. If omitted or empty, defaults to including all files.
30
- `exclude` (FilterPattern, optional): Picomatch patterns for files to exclude. Takes precedence over include patterns.
31
- `options.resolve` (string | false | null, optional): Base directory for pattern resolution:
32
- `string`: Use as base directory (relative paths resolved against `process.cwd()`)
33
- `false`: Don't resolve patterns (useful for virtual module names)
34
- `null` or omitted: Use `process.cwd()` as base
35
36
**Usage Examples:**
37
38
```typescript
39
import { createFilter } from "@rollup/pluginutils";
40
41
// Basic usage with include/exclude patterns
42
const filter = createFilter(
43
["src/**/*.js", "src/**/*.ts"], // include JS and TS files in src
44
["**/*.test.*", "**/*.spec.*"], // exclude test files
45
{ resolve: process.cwd() }
46
);
47
48
// Use in plugin
49
export default function myPlugin(options = {}) {
50
const filter = createFilter(options.include, options.exclude);
51
52
return {
53
transform(code, id) {
54
if (!filter(id)) return; // Skip files that don't match
55
56
// Process matching files...
57
return { code: processCode(code) };
58
}
59
};
60
}
61
62
// Virtual modules (no path resolution)
63
const virtualFilter = createFilter(
64
["virtual:*"],
65
null,
66
{ resolve: false }
67
);
68
69
// RegExp patterns
70
const regexFilter = createFilter([/\.worker\.js$/]);
71
```
72
73
### addExtension
74
75
Adds a file extension to a filename if one doesn't already exist.
76
77
```typescript { .api }
78
/**
79
* Adds an extension to a module ID if one does not exist
80
* @param filename - The filename to potentially add an extension to
81
* @param ext - The extension to add (defaults to '.js')
82
* @returns The filename with extension added if needed
83
*/
84
function addExtension(filename: string, ext?: string): string;
85
```
86
87
**Parameters:**
88
89
- `filename` (string): The filename to check and potentially modify
90
- `ext` (string, optional): The extension to add. Defaults to `'.js'`
91
92
**Usage Examples:**
93
94
```typescript
95
import { addExtension } from "@rollup/pluginutils";
96
97
// Basic usage - adds .js if no extension exists
98
addExtension('foo'); // 'foo.js'
99
addExtension('foo.js'); // 'foo.js' (unchanged)
100
addExtension('foo.bar'); // 'foo.bar' (unchanged)
101
102
// Custom extension
103
addExtension('foo', '.mjs'); // 'foo.mjs'
104
addExtension('foo.js', '.mjs'); // 'foo.js' (unchanged - already has extension)
105
106
// Use in plugin resolveId hook
107
export default function myPlugin() {
108
return {
109
resolveId(id) {
110
// Ensure all imports have .js extension
111
return addExtension(id);
112
}
113
};
114
}
115
```
116
117
### normalizePath
118
119
Converts Windows backslash path separators to forward slashes for cross-platform compatibility.
120
121
```typescript { .api }
122
/**
123
* Converts path separators to forward slash for cross-platform compatibility
124
* @param filename - The file path to normalize
125
* @returns Path with forward slashes
126
*/
127
function normalizePath(filename: string): string;
128
```
129
130
**Parameters:**
131
132
- `filename` (string): The file path to normalize
133
134
**Usage Examples:**
135
136
```typescript
137
import { normalizePath } from "@rollup/pluginutils";
138
139
// Windows paths converted to POSIX style
140
normalizePath('src\\components\\Button.js'); // 'src/components/Button.js'
141
normalizePath('C:\\Users\\dev\\project\\index.js'); // 'C:/Users/dev/project/index.js'
142
143
// POSIX paths unchanged
144
normalizePath('src/components/Button.js'); // 'src/components/Button.js'
145
146
// Use in plugin for consistent path handling
147
export default function myPlugin() {
148
return {
149
transform(code, id) {
150
const normalizedId = normalizePath(id);
151
152
// Use normalized path for logging, caching, etc.
153
console.log(`Processing: ${normalizedId}`);
154
155
return { code };
156
}
157
};
158
}
159
```
160
161
## Common Patterns
162
163
### Plugin File Processing Pipeline
164
165
```typescript
166
import { createFilter, addExtension, normalizePath } from "@rollup/pluginutils";
167
168
export default function myPlugin(options = {}) {
169
const filter = createFilter(options.include, options.exclude);
170
171
return {
172
resolveId(id, importer) {
173
// Normalize paths for consistent handling
174
const normalizedId = normalizePath(id);
175
176
// Add extension if missing
177
const resolvedId = addExtension(normalizedId);
178
179
return resolvedId;
180
},
181
182
load(id) {
183
const normalizedId = normalizePath(id);
184
185
// Only load files that match our filter
186
if (!filter(normalizedId)) return null;
187
188
// Load and return file content...
189
},
190
191
transform(code, id) {
192
const normalizedId = normalizePath(id);
193
194
// Filter files for transformation
195
if (!filter(normalizedId)) return null;
196
197
// Transform the code...
198
return { code: transformedCode };
199
}
200
};
201
}
202
```
203
204
### Advanced Filtering
205
206
```typescript
207
import { createFilter } from "@rollup/pluginutils";
208
209
// Multiple include patterns with complex exclusions
210
const complexFilter = createFilter(
211
[
212
"src/**/*.{js,ts,jsx,tsx}", // Source files
213
"lib/**/*.js", // Library files
214
/\.worker\.(js|ts)$/ // Worker files (RegExp)
215
],
216
[
217
"**/*.test.*", // Test files
218
"**/*.spec.*", // Spec files
219
"**/node_modules/**", // Dependencies
220
"**/*.d.ts" // Type definitions
221
],
222
{ resolve: "/project/root" } // Custom base directory
223
);
224
225
// Use with custom options from plugin configuration
226
export default function myPlugin(options = {}) {
227
const filter = createFilter(
228
options.include || ["**/*.{js,ts}"],
229
options.exclude || ["node_modules/**"],
230
{ resolve: options.baseDir || process.cwd() }
231
);
232
233
return {
234
transform(code, id) {
235
if (!filter(id)) return;
236
// Process file...
237
}
238
};
239
}
240
```