Skip to content

Commit

Permalink
fix(resolve): make tryNodeResolve more robust
Browse files Browse the repository at this point in the history
The "{id}/package.json" lookup done by `resolvePackageData` is insufficient for certain edge cases, like when "node_modules/{dep}" is linked to a directory without a package.json in it. With this PR, you can now import any file from node_modules even if it has no package.json file associated with it. This mirrors the same capability in Node's resolution algorithm.

In addition to supporting more edge cases, this new implementation might also be faster in some cases, since we are doing less lookups than compared to the previous behavior of calling `resolvePackageData` for every path in the `possiblePkgIds` array.
  • Loading branch information
aleclarson committed Nov 14, 2022
1 parent bb4fbd0 commit f62843d
Show file tree
Hide file tree
Showing 2 changed files with 241 additions and 127 deletions.
13 changes: 13 additions & 0 deletions packages/vite/src/node/packages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,16 @@ export function watchPackageDataPlugin(config: ResolvedConfig): Plugin {
}
}
}

export function findPackageJson(dir: string): string | null {
// Stop looking at node_modules directory.
if (path.basename(dir) === 'node_modules') {
return null
}
const pkgPath = path.join(dir, 'package.json')
if (fs.existsSync(pkgPath)) {
return pkgPath
}
const parentDir = path.dirname(dir)
return parentDir !== dir ? findPackageJson(parentDir) : null
}
Loading

0 comments on commit f62843d

Please sign in to comment.