Skip to content

Commit

Permalink
perf(resolve): findNearestMainPackageData instead of lookupFile (#12576)
Browse files Browse the repository at this point in the history
Co-authored-by: Bjorn Lu <bjornlu.dev@gmail.com>
  • Loading branch information
patak-dev and bluwy committed Mar 25, 2023
1 parent 8ab1438 commit 54b376f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 14 deletions.
17 changes: 17 additions & 0 deletions packages/vite/src/node/packages.ts
Expand Up @@ -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)
Expand Down
10 changes: 3 additions & 7 deletions packages/vite/src/node/plugins/resolve.ts
Expand Up @@ -31,7 +31,6 @@ import {
isOptimizable,
isTsRequest,
isWindows,
lookupFile,
normalizePath,
resolveFrom,
safeRealpathSync,
Expand All @@ -43,6 +42,7 @@ import type { DepsOptimizer } from '../optimizer'
import type { SSROptions } from '..'
import type { PackageCache, PackageData } from '../packages'
import {
findNearestMainPackageData,
findNearestPackageData,
loadPackageData,
resolvePackageData,
Expand Down Expand Up @@ -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
Expand Down
8 changes: 1 addition & 7 deletions packages/vite/src/node/utils.ts
Expand Up @@ -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(
Expand All @@ -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)
Expand Down

0 comments on commit 54b376f

Please sign in to comment.