36 lines
932 B
TypeScript
36 lines
932 B
TypeScript
import { Plugin } from 'vite'
|
|
import fs from 'fs'
|
|
import path from 'path'
|
|
|
|
interface FileWatcherOptions {
|
|
file: string;
|
|
fn: (content: string) => void;
|
|
delay?: number;
|
|
}
|
|
|
|
export function fileWatcher(options: FileWatcherOptions): Plugin {
|
|
const {file, fn, delay = 300} = options
|
|
let debounceTimer: NodeJS.Timeout | null = null
|
|
|
|
return {
|
|
name: 'file-watcher-plugin',
|
|
configureServer(server) {
|
|
server.watcher.add(path.resolve(file))
|
|
|
|
server.watcher.on('change', (filePath: string) => {
|
|
if (filePath === path.resolve(file)) {
|
|
if (debounceTimer) clearTimeout(debounceTimer)
|
|
debounceTimer = setTimeout(() => {
|
|
try {
|
|
const content = fs.readFileSync(filePath, 'utf-8')
|
|
fn(content)
|
|
} catch (error) {
|
|
console.error('文件变化处理失败:', error)
|
|
}
|
|
}, delay)
|
|
}
|
|
})
|
|
},
|
|
}
|
|
}
|