@@ -648,13 +648,36 @@ export function tryNodeResolve(
648
648
basedir = nestedResolveFrom ( nestedRoot , basedir , preserveSymlinks )
649
649
}
650
650
651
+ // nearest package.json
652
+ let nearestPkg : PackageData | undefined
653
+ // nearest package.json that may have the `exports` field
651
654
let pkg : PackageData | undefined
652
- const pkgId = possiblePkgIds . reverse ( ) . find ( ( pkgId ) => {
653
- pkg = resolvePackageData ( pkgId , basedir , preserveSymlinks , packageCache ) !
654
- return pkg
655
+
656
+ let pkgId = possiblePkgIds . reverse ( ) . find ( ( pkgId ) => {
657
+ nearestPkg = resolvePackageData (
658
+ pkgId ,
659
+ basedir ,
660
+ preserveSymlinks ,
661
+ packageCache
662
+ ) !
663
+ return nearestPkg
655
664
} ) !
656
665
657
- if ( ! pkg ) {
666
+ const rootPkgId = possiblePkgIds [ 0 ]
667
+ const rootPkg = resolvePackageData (
668
+ rootPkgId ,
669
+ basedir ,
670
+ preserveSymlinks ,
671
+ packageCache
672
+ ) !
673
+ if ( rootPkg ?. data ?. exports ) {
674
+ pkg = rootPkg
675
+ pkgId = rootPkgId
676
+ } else {
677
+ pkg = nearestPkg
678
+ }
679
+
680
+ if ( ! pkg || ! nearestPkg ) {
658
681
// if import can't be found, check if it's an optional peer dep.
659
682
// if so, we can resolve to a special id that errors only when imported.
660
683
if (
@@ -753,7 +776,8 @@ export function tryNodeResolve(
753
776
}
754
777
755
778
const ext = path . extname ( resolved )
756
- const isCJS = ext === '.cjs' || ( ext === '.js' && pkg . data . type !== 'module' )
779
+ const isCJS =
780
+ ext === '.cjs' || ( ext === '.js' && nearestPkg . data . type !== 'module' )
757
781
758
782
if (
759
783
! options . ssrOptimizeCheck &&
0 commit comments