diff --git a/packages/vite-plugin-svelte/src/index.ts b/packages/vite-plugin-svelte/src/index.ts index dcd17e018..f3325f1e3 100644 --- a/packages/vite-plugin-svelte/src/index.ts +++ b/packages/vite-plugin-svelte/src/index.ts @@ -13,7 +13,7 @@ import { } from './utils/options'; import { VitePluginSvelteCache } from './utils/vite-plugin-svelte-cache'; -import { setupWatchers } from './utils/watch'; +import { ensureWatchedFile, setupWatchers } from './utils/watch'; import { resolveViaPackageJsonSvelte } from './utils/resolve'; import { addExtraPreprocessors } from './utils/preprocess'; import { PartialResolvedId } from 'rollup'; @@ -164,7 +164,9 @@ export function svelte(inlineOptions?: Partial): Plugin { logCompilerWarnings(compileData.compiled.warnings, options); cache.update(compileData); if (compileData.dependencies?.length && options.server) { - compileData.dependencies.forEach((d) => this.addWatchFile(d)); + compileData.dependencies.forEach((d) => { + ensureWatchedFile(options.server!.watcher, d, options.root); + }); } log.debug(`transform returns compiled js for ${filename}`); return compileData.compiled.js; diff --git a/packages/vite-plugin-svelte/src/utils/watch.ts b/packages/vite-plugin-svelte/src/utils/watch.ts index 9d5cd7971..fed37dd51 100644 --- a/packages/vite-plugin-svelte/src/utils/watch.ts +++ b/packages/vite-plugin-svelte/src/utils/watch.ts @@ -5,6 +5,7 @@ import { IdParser } from './id'; import { ResolvedOptions } from './options'; import { knownSvelteConfigNames } from './load-svelte-config'; import path from 'path'; +import { FSWatcher } from 'vite'; export function setupWatchers( options: ResolvedOptions, @@ -71,22 +72,35 @@ export function setupWatchers( }; // collection of watcher listeners by event - const listeners = { - add: [], + const listenerCollection = { + add: [] as Array, change: [emitChangeEventOnDependants], unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants] }; if (svelteConfigFile) { - listeners.change.push(restartOnConfigChange); - listeners.unlink.push(restartOnConfigChange); + listenerCollection.change.push(restartOnConfigChange); + listenerCollection.unlink.push(restartOnConfigChange); } else { - // @ts-ignore - listeners.add.push(restartOnConfigAdd); + listenerCollection.add.push(restartOnConfigAdd); } - Object.entries(listeners).forEach(([evt, listeners]) => { + Object.entries(listenerCollection).forEach(([evt, listeners]) => { if (listeners.length > 0) { watcher.on(evt, (filename) => listeners.forEach((listener) => listener(filename))); } }); } +// taken from vite utils +export function ensureWatchedFile(watcher: FSWatcher, file: string | null, root: string): void { + if ( + file && + // only need to watch if out of root + !file.startsWith(root + '/') && + // some rollup plugins use null bytes for private resolved Ids + !file.includes('\0') && + fs.existsSync(file) + ) { + // resolve file to normalized system path + watcher.add(path.resolve(file)); + } +}