diff --git a/packages/vite/src/node/packages.ts b/packages/vite/src/node/packages.ts index 97fa19111870e2..9b35ecc3b82e9c 100644 --- a/packages/vite/src/node/packages.ts +++ b/packages/vite/src/node/packages.ts @@ -1,7 +1,12 @@ import fs from 'node:fs' import path from 'node:path' import { createRequire } from 'node:module' -import { createFilter, isInNodeModules, safeRealpathSync } from './utils' +import { + createFilter, + isInNodeModules, + safeRealpathSync, + tryStatSync, +} from './utils' import type { Plugin } from './plugin' let pnp: typeof import('pnpapi') | undefined @@ -125,8 +130,8 @@ export function findNearestPackageData( } const pkgPath = path.join(basedir, 'package.json') - try { - if (fs.statSync(pkgPath, { throwIfNoEntry: false })?.isFile()) { + if (tryStatSync(pkgPath)?.isFile()) { + try { const pkgData = loadPackageData(pkgPath) if (packageCache) { @@ -134,8 +139,8 @@ export function findNearestPackageData( } return pkgData - } - } catch {} + } catch {} + } const nextBasedir = path.dirname(basedir) if (nextBasedir === basedir) break diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index be53f4c0636e6c..843d06ed5c6159 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -386,6 +386,7 @@ export function isDefined(value: T | undefined | null): value is T { export function tryStatSync(file: string): fs.Stats | undefined { try { + // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist return fs.statSync(file, { throwIfNoEntry: false }) } catch { // Ignore errors @@ -501,12 +502,11 @@ export function generateCodeFrame( } export function isFileReadable(filename: string): boolean { - try { - // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist - if (!fs.statSync(filename, { throwIfNoEntry: false })) { - return false - } + if (!tryStatSync(filename)) { + return false + } + try { // Check if current process has read permission to the file fs.accessSync(filename, fs.constants.R_OK)