When using dynamic imports, multiple imports to the same module generate separate Promises. Caching allows handling imports to the same path with a single Promise.
type ModuleCache = Map<string, Promise<unknown>>;
const modCache: ModuleCache = new Map();
export async function dynamicImport<T = unknown>(path: string): Promise<T> { const cache = modCache.get(path); if (cache) return cache as Promise<T>;
const modPromise = import(path) as Promise<T>; modCache.set(path, modPromise); return modPromise;}Where It Pays Off in Practice
This pattern is most useful when parallel imports can hit the same module at the same time. It works well for lazy dialogs, admin widgets, or command palettes where multiple callers can trigger the same import race.
The main design choice is whether failed Promises should stay in the cache. If the requirement includes retry, it is usually easier to clear the cache entry on error.
Practical Note
This snippet fits well when I do not want to rewrite the same operation or check around typescript, javascript, performance over and over. Keeping it as a small helper makes the caller easier to read because the intent stays in the foreground.
If the branches and preconditions start growing, it is usually better not to force everything into one snippet. Splitting the steps and helper responsibilities is easier to maintain.
Implementation Note
For reuse, it helps to decide the input, output, and side effects first. With Dynamic Import Caching, the call site stays clearer when it is obvious what this snippet is trying to shorten in the typescript, javascript, performance context.
Not every precondition needs to live inside the same block. The result is usually steadier when the caller responsibility and the snippet responsibility stay separate.
hsb.horse