0
# File Watching
1
2
Development-focused file watching system for automatic CSS regeneration when source files change, providing hot reload functionality for UnoCSS development workflows.
3
4
## Capabilities
5
6
### Get Watcher
7
8
Creates or returns existing chokidar file system watcher for monitoring file changes during development.
9
10
```typescript { .api }
11
/**
12
* Creates or returns existing chokidar file system watcher
13
* @param options - CLI options containing patterns and working directory
14
* @returns Promise resolving to FSWatcher instance for file monitoring
15
*/
16
function getWatcher(options?: CliOptions): Promise<FSWatcher>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
// Note: getWatcher may not be directly exported from main package entry
23
import { getWatcher } from "@unocss/cli";
24
25
// Create watcher for HTML files
26
const watcher = await getWatcher({
27
patterns: ["src/**/*.html"],
28
cwd: process.cwd(),
29
});
30
31
// Listen for file changes
32
watcher.on('change', (path) => {
33
console.log(`File changed: ${path}`);
34
});
35
36
watcher.on('add', (path) => {
37
console.log(`File added: ${path}`);
38
});
39
40
watcher.on('unlink', (path) => {
41
console.log(`File removed: ${path}`);
42
});
43
44
// Close watcher when done
45
process.on('SIGINT', () => {
46
watcher.close();
47
});
48
```
49
50
### Watch Configuration
51
52
The watcher is configured with sensible defaults for web development:
53
54
- **Ignored directories**: Automatically ignores `node_modules` and `.git` directories
55
- **Permission handling**: Ignores permission errors that might occur on some systems
56
- **Initial scan**: Skips initial file scan (`ignoreInitial: true`) to avoid triggering on startup
57
- **Singleton pattern**: Returns the same watcher instance for efficiency
58
59
## Integration with Build Process
60
61
When watch mode is enabled in the build function, the following workflow occurs:
62
63
1. **Initial Build**: Performs complete CSS generation from all files
64
2. **Watcher Setup**: Creates file system watcher for specified patterns
65
3. **Configuration Monitoring**: Also watches UnoCSS configuration files for changes
66
4. **Change Detection**: Monitors both source files and configuration files
67
5. **Debounced Rebuilds**: Uses debouncing to prevent excessive rebuilds
68
6. **Cache Management**: Updates file cache when files change
69
7. **Automatic Regeneration**: Rebuilds CSS automatically when changes are detected
70
71
### Watch Mode Examples
72
73
```typescript
74
import { build } from "@unocss/cli";
75
76
// Basic watch mode
77
await build({
78
patterns: ["src/**/*.{html,js,ts}"],
79
outFile: "dist/uno.css",
80
watch: true,
81
});
82
83
// Watch with custom configuration
84
await build({
85
patterns: ["src/**/*.html", "components/**/*.jsx"],
86
outFile: "public/styles.css",
87
watch: true,
88
config: "uno.config.js",
89
preflights: true,
90
});
91
```
92
93
### Manual Watcher Usage
94
95
For advanced use cases, you can create and manage watchers manually:
96
97
```typescript
98
import { getWatcher } from "@unocss/cli";
99
import { debounce } from "perfect-debounce";
100
101
// Create custom watcher setup
102
const watcher = await getWatcher({
103
patterns: ["src/**/*.{html,js,vue}"],
104
cwd: "/path/to/project",
105
});
106
107
// Custom debounced rebuild function
108
const debouncedRebuild = debounce(async () => {
109
console.log("Rebuilding CSS...");
110
// Your custom rebuild logic here
111
}, 100);
112
113
// Handle different file events
114
watcher.on('all', (event, path) => {
115
console.log(`${event}: ${path}`);
116
117
if (event === 'change' || event === 'add') {
118
debouncedRebuild();
119
}
120
});
121
122
// Graceful shutdown
123
process.on('SIGTERM', () => {
124
watcher.close();
125
});
126
```
127
128
## File Change Handling
129
130
The watch system handles different types of file changes appropriately:
131
132
### Source File Changes
133
134
- **File Added**: Adds new file to cache and triggers rebuild
135
- **File Modified**: Updates cached content and triggers rebuild
136
- **File Deleted**: Removes file from cache and triggers rebuild
137
138
### Configuration File Changes
139
140
- **Config Modified**: Reloads UnoCSS configuration and triggers full rebuild
141
- **Config Added**: Starts monitoring new configuration file
142
- **Config Deleted**: Falls back to default configuration
143
144
### Logging and Feedback
145
146
The watch system provides detailed console feedback:
147
148
```bash
149
UnoCSS v66.5.0
150
✨ UnoCSS in watch mode...
151
ℹ Watching for changes in src/**/*.html, src/**/*.js
152
153
change src/index.html
154
✅ 15 utilities generated to dist/uno.css
155
156
add src/components/button.html
157
✅ 23 utilities generated to dist/uno.css
158
159
uno.config.js changed, setting new config
160
✅ 23 utilities generated to dist/uno.css
161
```
162
163
## Performance Considerations
164
165
- **Debouncing**: File changes are debounced (100ms) to prevent excessive rebuilds
166
- **Selective Processing**: Only processes files that have actually changed
167
- **Efficient Caching**: Maintains in-memory file cache to avoid unnecessary disk reads
168
- **Singleton Watcher**: Reuses watcher instances to minimize resource usage