How should the TypeScript compiler API's 'module resolution cache' be used?

Viewed 540

I noticed that ts.resolveModuleName has an optional cache parameter and an accompanying resolveModuleNameFromCache function. I assume they have something to do with caching resolved module names to improve performance, but it's not clear to me how (and if) they should be used.

I'd love to get a better general understanding of these caches, but for now I have two concrete questions:

  1. What should be passed into the currentDirectory parameter for createModuleResolutionCache?
  2. Does resolveModuleNameFromCache literally mean "resolving from just the cache", or will it fall back to the 'hard work' if necessary?

Again, I'd love to get a better general understanding of these caches, but answers to these questions would already be a nice step in the right direction.

1 Answers

The module resolution cache is a way to cache the result of previous calls for resolving a module name.

Internally it's a standard:

let result = cache.get(key);
if (!result) {
    result = create();
    cache.set(key, result);
}
return result;

An example of it being used can be seen here in rollup. I would say it's probably preferable to use, but I have no clue what the performance impact is like.

  1. What should be passed into the currentDirectory parameter for createModuleResolutionCache?

If you have a compiler host or program, then you should provide the result of CompilerHost#getCurrentDirectory() or Program#getCurrentDirectory(). If you don't have either, then use ts.sys.getCurrentDirectory(), which is the default when using ts.createCompilerHost.

  1. Does resolveModuleNameFromCache literally mean "resolving from just the cache", or will it fall back to the 'hard work' if necessary?

It won't do any of the hard work and will only try to get the name from the cache. Here's the current code in the compiler (.get(moduleName) is a Map#get):

export function resolveModuleNameFromCache(
    moduleName: string,
    containingFile: string,
    cache: ModuleResolutionCache
): ResolvedModuleWithFailedLookupLocations | undefined {
    const containingDirectory = getDirectoryPath(containingFile);
    const perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
    return perFolderCache && perFolderCache.get(moduleName);
}
Related