diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index c0bc0646f58336..23c7597bb77195 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -951,12 +951,17 @@ export const requireResolveFromRootWithFallback = ( root: string, id: string ): string => { + const paths = _require.resolve.paths?.(id) || [] // Search in the root directory first, and fallback to the default require paths. - const fallbackPaths = _require.resolve.paths?.(id) || [] - const path = _require.resolve(id, { - paths: [root, ...fallbackPaths] - }) - return path + paths.unshift(root) + + // Use `resolve` package to check existence first, so if the package is not found, + // it won't be cached by nodejs, since there isn't a way to invalidate them: + // https://github.com/nodejs/node/issues/44663 + resolve.sync(id, { basedir: root, paths }) + + // Use `require.resolve` again as the `resolve` package doesn't support the `exports` field + return _require.resolve(id, { paths }) } // Based on node-graceful-fs