1
1
import fs from 'node:fs'
2
2
import path from 'node:path'
3
- import { createDebugger , createFilter , resolveFrom } from './utils'
3
+ import { createRequire } from 'node:module'
4
+ import { createDebugger , createFilter , safeRealpathSync } from './utils'
4
5
import type { ResolvedConfig } from './config'
5
6
import type { Plugin } from './plugin'
6
7
8
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
9
+ let pnp : typeof import ( 'pnpapi' ) | undefined
10
+ if ( process . versions . pnp ) {
11
+ try {
12
+ pnp = createRequire ( import . meta. url ) ( 'pnpapi' )
13
+ } catch { }
14
+ }
15
+
7
16
const isDebug = process . env . DEBUG
8
17
const debug = createDebugger ( 'vite:resolve-details' , {
9
18
onlyWhenFocused : true ,
@@ -60,9 +69,9 @@ export function resolvePackageData(
60
69
return pkg
61
70
}
62
71
}
63
- let pkgPath : string | undefined
72
+ const pkgPath = resolvePkgJsonPath ( id , basedir , preserveSymlinks )
73
+ if ( ! pkgPath ) return null
64
74
try {
65
- pkgPath = resolveFrom ( `${ id } /package.json` , basedir , preserveSymlinks )
66
75
pkg = loadPackageData ( pkgPath , true , packageCache )
67
76
if ( packageCache ) {
68
77
packageCache . set ( cacheKey ! , pkg )
@@ -72,12 +81,8 @@ export function resolvePackageData(
72
81
if ( e instanceof SyntaxError ) {
73
82
isDebug && debug ( `Parsing failed: ${ pkgPath } ` )
74
83
}
75
- // Ignore error for missing package.json
76
- else if ( e . code !== 'MODULE_NOT_FOUND' ) {
77
- throw e
78
- }
84
+ throw e
79
85
}
80
- return null
81
86
}
82
87
83
88
export function loadPackageData (
@@ -86,7 +91,7 @@ export function loadPackageData(
86
91
packageCache ?: PackageCache ,
87
92
) : PackageData {
88
93
if ( ! preserveSymlinks ) {
89
- pkgPath = fs . realpathSync . native ( pkgPath )
94
+ pkgPath = safeRealpathSync ( pkgPath )
90
95
}
91
96
92
97
let cached : PackageData | undefined
@@ -178,3 +183,30 @@ export function watchPackageDataPlugin(config: ResolvedConfig): Plugin {
178
183
} ,
179
184
}
180
185
}
186
+
187
+ export function resolvePkgJsonPath (
188
+ pkgName : string ,
189
+ basedir : string ,
190
+ preserveSymlinks = false ,
191
+ ) : string | undefined {
192
+ if ( pnp ) {
193
+ const pkg = pnp . resolveToUnqualified ( pkgName , basedir )
194
+ if ( ! pkg ) return undefined
195
+ return path . join ( pkg , 'package.json' )
196
+ }
197
+
198
+ let root = basedir
199
+ while ( root ) {
200
+ const pkg = path . join ( root , 'node_modules' , pkgName , 'package.json' )
201
+ try {
202
+ if ( fs . existsSync ( pkg ) ) {
203
+ return preserveSymlinks ? pkg : safeRealpathSync ( pkg )
204
+ }
205
+ } catch { }
206
+ const nextRoot = path . dirname ( root )
207
+ if ( nextRoot === root ) break
208
+ root = nextRoot
209
+ }
210
+
211
+ return undefined
212
+ }
0 commit comments