forked from posva/unplugin-vue-router
/
RoutesFolderWatcher.ts
63 lines (55 loc) · 1.38 KB
/
RoutesFolderWatcher.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import chokidar from 'chokidar'
import { normalize } from 'pathe'
import { ResolvedOptions, RoutesFolderOption } from '../options'
export class RoutesFolderWatcher {
src: string
pathPrefix: string
watcher: chokidar.FSWatcher
options: ResolvedOptions
constructor(routesFolder: RoutesFolderOption, options: ResolvedOptions) {
this.src = routesFolder.src
this.pathPrefix = routesFolder.path || ''
this.options = options
this.watcher = chokidar.watch(this.src, {
ignoreInitial: true,
// disableGlobbing: true,
ignorePermissionErrors: true,
ignored: options.exclude,
// useFsEvents: true,
// TODO: allow user options
})
}
asRoutePath(path: string) {
return this.pathPrefix + path.slice(this.src.length + 1)
}
on(
event: 'add' | 'change' | 'unlink',
handler: (context: HandlerContext) => void
) {
this.watcher.on(event, (filePath) => {
filePath = normalize(filePath)
// skip other extensions
if (
this.options.extensions.every(
(extension) => !filePath.endsWith(extension)
)
) {
return
}
handler({
filePath,
routePath: this.asRoutePath(filePath),
})
})
return this
}
close() {
this.watcher.close()
}
}
export interface HandlerContext {
// resolved path
filePath: string
// routePath
routePath: string
}