import _ from 'lodash'; import path from 'path'; import chokidar from 'chokidar'; import logger from './logger'; export function watchDir(dir: string, onFileChange: (filePaths: string[]) => void, throttleDelay = 1000): chokidar.FSWatcher { const fullDir = path.resolve(process.cwd(), dir); logger.debug('Watch dir for changes: ' + fullDir); const watcher = chokidar.watch('.', { cwd: fullDir, ignored: (filePath) => { return ( filePath.includes(`/.git/`) || filePath.includes(`/.next/`) || filePath.includes(`/.cache/`) || filePath.includes(`/.stackbit/cache`) || filePath.includes(`/node_modules`) || ((filePath.includes(`/.`) || filePath.startsWith(`.`)) && !(filePath.includes(`/.stackbit`) || filePath.startsWith(`.stackbit`))) ); }, persistent: true, ignoreInitial: true }); let changedFiles: string[] = []; const throttledFileChange = _.throttle(() => { if (changedFiles.length) { onFileChange(changedFiles); changedFiles = []; } }, throttleDelay); const handleFileChange = (filePath: string) => { if (!changedFiles.includes(filePath)) { changedFiles.push(filePath); } throttledFileChange(); }; watcher .on('add', handleFileChange) .on('change', handleFileChange) .on('unlink', handleFileChange) .on('addDir', handleFileChange) .on('unlinkDir', handleFileChange); return watcher; }