Skip to content

Commit

Permalink
Use host.resolveModuleNames when available
Browse files Browse the repository at this point in the history
TSC allows users to configure module resolution by implementing
host.resolveModuleNames. This is used both by Deno and ChiselStrike.

Unfortunately, I couldn't find an exported TSC function that uses
host.resolveModuleNames or the builtin resolution, so I implemented
the logic in the type-compiler.
  • Loading branch information
espindola committed Jul 7, 2022
1 parent 78b8559 commit 9280412
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions packages/type-compiler/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
Expression,
ImportDeclaration,
resolveModuleName,
ResolvedModule,
ScriptTarget,
SourceFile,
StringLiteral,
Expand All @@ -32,6 +33,14 @@ export class Resolver {
return this.resolveSourceFile(from.fileName, (moduleSpecifier as StringLiteral).text);
}

resolveImpl(modulePath: string, fromPath: string): ResolvedModule | undefined {
if (this.host.resolveModuleNames !== undefined) {
return this.host.resolveModuleNames([modulePath], fromPath, /*reusedNames*/ undefined, /*redirectedReference*/ undefined, this.compilerOptions)[0];
}
const result = resolveModuleName(modulePath, fromPath, this.compilerOptions, this.host);
return result.resolvedModule;
}

/**
* Tries to resolve the d.ts file path for a given module path.
* Scans relative paths. Looks into package.json "types" and "exports" (with new 4.7 support)
Expand All @@ -40,13 +49,13 @@ export class Resolver {
* @param modulePath the x in 'from x'.
*/
resolveSourceFile(fromPath: string, modulePath: string): SourceFile | undefined {
const result = resolveModuleName(modulePath, fromPath, this.compilerOptions, this.host);
if (!result.resolvedModule) return;
const result = this.resolveImpl(modulePath, fromPath);
if (!result) return;

const fileName = result.resolvedModule.resolvedFileName;
const fileName = result.resolvedFileName;
if (this.sourceFiles[fileName]) return this.sourceFiles[fileName];

const source = this.host.readFile(result.resolvedModule.resolvedFileName);
const source = this.host.readFile(result.resolvedFileName);
if (!source) return;
const sourceFile = this.sourceFiles[fileName] = createSourceFile(fileName, source, this.compilerOptions.target || ScriptTarget.ES2018, true);

Expand Down

0 comments on commit 9280412

Please sign in to comment.