njzscloud-dispose-web/plugin/file-watcher.ts

33 lines
950 B
TypeScript

import type { Plugin } from 'vite'
import fs from 'fs'
/**
* 文件监视器插件
* @param options
*/
export function fileWatcher(...options: VitePluginTypes.FileWatcherOptions[]): Plugin {
console.log(`启动文件监听器,处理器数量:${options == null ? 0 : options.length}`)
return {
name: 'file-watcher-plugin',
configureServer(server) {
server.watcher
.on('all', (event, filePath, stats) => {
if (options == null || options.length === 0) return
options.forEach(it => {
const isDir = stats!.isDirectory()
const getContent = () => {
return isDir ? '' : fs.readFileSync(filePath, 'utf-8')
}
const isAccept = it.isAccept({event, filePath, isDir})
if (isAccept) {
it.process({
event, filePath, isDir, getContent,
})
}
})
})
},
}
}