Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Key a generic dynamic-import memoization cache by an explicit string, not by the thunk
When writing a reusable `loadModule(key, () => import('...'))`-style helper that memoizes in-flight dynamic imports across multiple call sites, key the cache by an explicit string, not by the thunk reference — and keep the `import()` call itself written out inline in each call site, because bundlers only code-split `import()` calls whose specifier is a literal string.
Bad example
| 1 | const pending = new Map<Function, Promise<unknown>>(); |
| 2 |
|
| 3 | export function loadModule<T>(importFn: () => Promise<T>) { |
| 4 | let p = pending.get(importFn); |
| 5 | if (!p) { |
| 6 | p = importFn(); |
| 7 | pending.set(importFn, p); |
| 8 | } |
| 9 | return p as Promise<T>; |
| 10 | } |
| 11 |
|
| 12 | // call site |
| 13 | loadModule(() => import('./chart-lib')); |
Explanation (EN)
Every call passes a fresh inline arrow function, so the Map key never matches across calls — the memoization never hits and the module is fetched again each time.
Objašnjenje (HR)
Svaki poziv prosljeđuje novu inline streličastu funkciju, pa se ključ u Mapi nikad ne poklapa između poziva — memoizacija nikad ne pogađa i modul se ponovno dohvaća svaki put.
Good example
| 1 | const pending = new Map<string, Promise<unknown>>(); |
| 2 |
|
| 3 | export function loadModule<T>(key: string, importFn: () => Promise<T>) { |
| 4 | let p = pending.get(key); |
| 5 | if (!p) { |
| 6 | p = importFn(); |
| 7 | pending.set(key, p); |
| 8 | } |
| 9 | return p as Promise<T>; |
| 10 | } |
| 11 |
|
| 12 | // call site — the import() specifier stays a literal so the bundler can still code-split it |
| 13 | loadModule('chart-lib', () => import('./chart-lib')); |
Explanation (EN)
An explicit string key correctly dedupes concurrent callers, while keeping the literal import() specifier inline preserves the bundler's ability to split that chunk.
Objašnjenje (HR)
Eksplicitni string ključ ispravno deduplicira istovremene pozive, a zadržavanje doslovnog import() specifikatora unutar poziva omogućuje bundleru da i dalje razdvoji taj chunk.