diff --git a/packages/vite/src/node/packages.ts b/packages/vite/src/node/packages.ts index 728c941051f72f..b4a0d7948240e6 100644 --- a/packages/vite/src/node/packages.ts +++ b/packages/vite/src/node/packages.ts @@ -143,6 +143,23 @@ export function findNearestPackageData( return null } +// Finds the nearest package.json with a `name` field +export function findNearestMainPackageData( + basedir: string, + packageCache?: PackageCache, +): PackageData | null { + const nearestPackage = findNearestPackageData(basedir, packageCache) + return ( + nearestPackage && + (nearestPackage.data.name + ? nearestPackage + : findNearestMainPackageData( + path.dirname(nearestPackage.dir), + packageCache, + )) + ) +} + export function loadPackageData(pkgPath: string): PackageData { const data = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) const pkgDir = path.dirname(pkgPath) diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 4d535c8659f834..bb1cadca3e9cd5 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -31,7 +31,6 @@ import { isOptimizable, isTsRequest, isWindows, - lookupFile, normalizePath, resolveFrom, safeRealpathSync, @@ -43,6 +42,7 @@ import type { DepsOptimizer } from '../optimizer' import type { SSROptions } from '..' import type { PackageCache, PackageData } from '../packages' import { + findNearestMainPackageData, findNearestPackageData, loadPackageData, resolvePackageData, @@ -705,12 +705,8 @@ export function tryNodeResolve( !id.includes('\0') && bareImportRE.test(id) ) { - // find package.json with `name` as main - const mainPackageJson = lookupFile(basedir, ['package.json'], { - predicate: (content) => !!JSON.parse(content).name, - }) - if (mainPackageJson) { - const mainPkg = JSON.parse(mainPackageJson) + const mainPkg = findNearestMainPackageData(basedir, packageCache)?.data + if (mainPkg) { if ( mainPkg.peerDependencies?.[id] && mainPkg.peerDependenciesMeta?.[id]?.optional diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 5e9a73f111f3b8..d1b3eb14cae7c8 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -389,7 +389,6 @@ export function tryStatSync(file: string): fs.Stats | undefined { interface LookupFileOptions { pathOnly?: boolean rootDir?: string - predicate?: (file: string) => boolean } export function lookupFile( @@ -400,12 +399,7 @@ export function lookupFile( for (const format of formats) { const fullPath = path.join(dir, format) if (tryStatSync(fullPath)?.isFile()) { - const result = options?.pathOnly - ? fullPath - : fs.readFileSync(fullPath, 'utf-8') - if (!options?.predicate || options.predicate(result)) { - return result - } + return options?.pathOnly ? fullPath : fs.readFileSync(fullPath, 'utf-8') } } const parentDir = path.dirname(dir)