diff --git a/packages/nx/src/utils/target-project-locator.ts b/packages/nx/src/utils/target-project-locator.ts index b5d867195d6150..a680d6b93657bd 100644 --- a/packages/nx/src/utils/target-project-locator.ts +++ b/packages/nx/src/utils/target-project-locator.ts @@ -17,7 +17,6 @@ export class TargetProjectLocator { private tsConfig = this.getRootTsConfig(); private paths = this.tsConfig.config?.compilerOptions?.paths; private typescriptResolutionCache = new Map(); - private projectResolutionCache = new Map(); private npmResolutionCache = new Map(); constructor( @@ -52,12 +51,6 @@ export class TargetProjectLocator { } } - // check if it exists in projects - const project = this.findProject(normalizedImportExpr); - if (project) { - return project; - } - // try to find npm package before using expensive typescript resolution const npmProject = this.findNpmPackage(normalizedImportExpr); if (npmProject) { @@ -77,6 +70,10 @@ export class TargetProjectLocator { } } + try { + this.resolveImportWithRequire(normalizedImportExpr, filePath); + } catch {} + // nothing found, cache for later this.npmResolutionCache.set(normalizedImportExpr, undefined); return null; @@ -135,22 +132,21 @@ export class TargetProjectLocator { return; } - private findProject(importExpr: string): string | undefined { - if (this.projectResolutionCache.has(importExpr)) { - return this.projectResolutionCache.get(importExpr); - } else { - const project = Object.values(this.nodes).find( - (project) => - importExpr === project.name || - importExpr.startsWith(`${project.name}/`) - ); - if (project) { - this.projectResolutionCache.set(importExpr, project.name); - return project.name; - } - } - } + private resolveImportWithRequire( + normalizedImportExpr: string, + filePath: string + ) { + const resolvedPathRelativeFromWorkspaceRoot = posix.relative( + workspaceRoot, + require.resolve(normalizedImportExpr, { + paths: [dirname(filePath)], + }) + ); + return this.findProjectOfResolvedModule( + resolvedPathRelativeFromWorkspaceRoot + ); + } private findNpmPackage(npmImport: string): string | undefined { if (this.npmResolutionCache.has(npmImport)) { return this.npmResolutionCache.get(npmImport);