From 3ba45b9a19df434b2195e4d5574f80c7426a3ba1 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Wed, 9 Nov 2022 17:36:04 +0800 Subject: [PATCH] fix: prevent cache on optional package resolve (v3) (#10812) (#10845) --- packages/vite/src/node/utils.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index f8aab87a13d96b..507ac7cb461dd9 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