TypeScript Compiler API
ts.createModuleResolutionCache()
Creates a reusable cache for compiler module resolution. Match directory, canonical naming, compiler options and host filesystem assumptions. Cached success or failure can become stale after changes; clear or recreate the cache on relevant invalidations. It is not a runtime module cache. Baseline: TypeScript 5.8.3 and Node.js. The example is a local tooling script in a disposable directory; it writes temporary project files, not a ByteMind CodeRunner exercise.
Formal Syntax & Structure
typescript syntaxtypescript
ts.createModuleResolutionCache(currentDirectory: string, getCanonicalFileName: (s: string) => string, options?: ts.CompilerOptions, packageJsonInfoCache?: ts.PackageJsonInfoCache): ts.ModuleResolutionCacheParameters & Attributes
| Name | Type | Description |
|---|---|---|
| currentDirectory | string | Resolution base directory. |
| getCanonicalFileName | (s: string) => string | Canonical path naming policy. |
| options | ts.CompilerOptions | Optional compatible resolution options. |
| packageJsonInfoCache | ts.PackageJsonInfoCache | Optional compatible package metadata cache. |
Working Example
Example Snippettypescript
// Use a new empty directory. Install: npm install --save-exact typescript@5.8.3// File: example.cjs (omit this label)const ts = require("typescript");const assert = require("node:assert/strict");const fs = require("node:fs");const path = require("node:path");const options={moduleResolution:ts.ModuleResolutionKind.Node10};const canon=ts.sys.useCaseSensitiveFileNames ? s=>s : s=>s.toLowerCase();const cache=ts.createModuleResolutionCache(process.cwd(),canon,options);const main=path.resolve("main.ts"); fs.writeFileSync(main,"");const resolve=()=>ts.resolveModuleName("./dep",main,options,ts.sys,cache).resolvedModule;assert.equal(resolve(),undefined); fs.writeFileSync("dep.ts","export const n=1;");assert.equal(resolve(),undefined); cache.clear();assert.equal(path.resolve(resolve().resolvedFileName),path.resolve("dep.ts"));console.log("missing -> cached missing -> resolved after clear");
// Run: node example.cjs// Expected stdout: missing -> cached missing -> resolved after clear