Skip to content

Commit

Permalink
fix(core): use require.resolve instead of randomly matching from our …
Browse files Browse the repository at this point in the history
…project graph
  • Loading branch information
FrozenPandaz committed Jan 20, 2023
1 parent 4c23648 commit 8185c36
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions packages/nx/src/utils/target-project-locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export class TargetProjectLocator {
private tsConfig = this.getRootTsConfig();
private paths = this.tsConfig.config?.compilerOptions?.paths;
private typescriptResolutionCache = new Map<string, string | null>();
private projectResolutionCache = new Map<string, string | null>();
private npmResolutionCache = new Map<string, string | null>();

constructor(
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 8185c36

Please sign in to comment.