logo hsb.horse
← Back to snippets index

Snippets

Dynamic Import Caching

Lightweight TypeScript implementation for caching dynamic imports. Handle multiple imports to the same path with a single Promise.

Published: Updated:

Translations

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;
}