import { subscribe } from '@parcel/watcher'; import { debounce } from 'es-toolkit'; import fs from 'node:fs'; import { projectPath } from "./common"; // 每个路径独立的防抖处理函数 const debouncedHandlers = new Map>(); const subscription = await subscribe( projectPath, // 监听路径(支持数组) async (err, events) => { if (err) throw err; for (const event of events) { // 如果已有防抖函数,先取消 if (debouncedHandlers.has(event.path)) { debouncedHandlers.get(event.path)?.cancel(); } // 为每个路径创建独立的防抖处理 const handler = debounce(() => { console.log(event.type, event.path, new Date()); // 'create', 'update', 'delete'... if (!fs.statSync(event.path).isFile()) return; // 跳过非文件事件 // event: { type: 'update', path: '/path/to/file.ts', file: true } debouncedHandlers.delete(event.path); }, 300); debouncedHandlers.set(event.path, handler); handler(); } }, { ignore: ['**/node_modules/**', '**/.git/**'], backend: 'watchman', // 可选:'fs-events'(默认)、'inotify'、'windows'、'watchman' } ); // 后续可取消监听 // await subscription.unsubscribe();