diff --git a/packages/vite-node/src/server.ts b/packages/vite-node/src/server.ts index de68171d5539..0a137b25f383 100644 --- a/packages/vite-node/src/server.ts +++ b/packages/vite-node/src/server.ts @@ -195,6 +195,30 @@ export class ViteNodeServer { return 'web' } + private getChangedModule( + id: string, + file: string, + ) { + const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file) + if (module) + return module + const _modules = this.server.moduleGraph.getModulesByFile(file) + if (!_modules || !_modules.size) + return null + // find the latest changed module + const modules = [..._modules] + let mod = modules[0] + let latestMax = -1 + for (const m of _modules) { + const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp) + if (timestamp > latestMax) { + latestMax = timestamp + mod = m + } + } + return mod + } + private async _fetchModule(id: string, transformMode: 'web' | 'ssr'): Promise { let result: FetchResult @@ -212,7 +236,7 @@ export class ViteNodeServer { const { path: filePath } = toFilePath(id, this.server.config.root) - const moduleNode = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(filePath) + const moduleNode = this.getChangedModule(id, filePath) const cache = this.fetchCaches[transformMode].get(filePath) // lastUpdateTimestamp is the timestamp that marks the last time the module was changed diff --git a/packages/vitest/src/node/core.ts b/packages/vitest/src/node/core.ts index 2a5d94693fc1..c9d531b16c95 100644 --- a/packages/vitest/src/node/core.ts +++ b/packages/vitest/src/node/core.ts @@ -705,6 +705,12 @@ export class Vitest { this.changedTests.add(id) this.scheduleRerun([id]) } + else { + // it's possible that file was already there but watcher triggered "add" event instead + const needsRerun = this.handleFileChanged(id) + if (needsRerun.length) + this.scheduleRerun(needsRerun) + } } const watcher = this.server.watcher