microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
101.17k stars 12.51k forks source link

Exposing canonical filename logic #37772

Open HoldYourWaffle opened 4 years ago

HoldYourWaffle commented 4 years ago

Search Terms

canonical filename

Suggestion

I'd like to re-use the get-canonical-filename logic: https://github.com/microsoft/TypeScript/blob/d68295e74e4897f588e73edf72089eb238904f02/src/compiler/core.ts#L1906-L1909

Use Cases

I want to use ts.resolveModuleName and the accompanying ts.createModuleResolutionCache to resolve ImportDeclarations (as per this comment's suggestion). createModuleResolutionCache requires a parameter getCanonicalFileName. I think it makes the most sense to use the same logic as the compiler itself here, which is the function I linked above.

I could just copy-and-paste this function, but that feels wrong and might lead to discrepancies in the future if toFileNameLowerCase (which is not exposed either) is ever updated.

Examples

const cache = ts.createModuleResolutionCache(currentDirectory, ts.createGetCanonicalFileName(true/false));
const resolved = ts.resolveModuleName(name, file, compilerOptions, host, cache);

Checklist

My suggestion meets these guidelines:

sheetalkamat commented 4 years ago

Instead of exposing createGetCanonicalFileName we need to make createModuleResolutionCache accept caseSensitive as well.

HoldYourWaffle commented 4 years ago

Yeah, that probably makes more sense. I assume I'd be able to use compilerHost.useCaseSensitiveFileNames to get the appropriate value?

HoldYourWaffle commented 4 years ago

I just noticed that CompilerHost provides access to a getCanonicalFileName method: https://github.com/microsoft/TypeScript/blob/f31b5a278f03b2e2d2713ed64230f853ae6b4545/lib/typescript.d.ts#L2926-L2934

A workaround for my specific usecase could thus be:

const host = ts.createCompilerHost(compilerOptions); //ugly, but necessary when using the transformer API (#37754)
const cache = ts.createModuleResolutionCache(currentDirectory, host.getCanonicalFileName, compilerOptions);