Rules Hub
Coding Rules Library
Colocate polyfills with their dependent libraries
Wrap libraries that require polyfills in a dedicated module to encapsulate side effects and clarify dependencies.
Bad example
| 1 | // src/utils.ts |
| 2 | import './polyfills/string-replace-all'; // Unclear why this is here |
| 3 | import { formatDate } from './date'; |
| 4 | import legacyLib from 'legacy-text-processor'; |
| 5 |
|
| 6 | export const processText = (text: string) => { |
| 7 | // It works, but the dependency between the polyfill and legacyLib is hidden |
| 8 | return legacyLib.format(text); |
| 9 | }; |
Explanation (EN)
The polyfill is imported in a generic utility file. It is unclear which library requires it, and if 'legacyLib' is removed in the future, the polyfill will likely remain as dead code because the relationship is not explicit.
Objašnjenje (HR)
Polyfill je importan u općenitu utility datoteku. Nije jasno koja biblioteka ga zahtijeva, a ako se 'legacyLib' ukloni u budućnosti, polyfill će vjerojatno ostati kao mrtav kod jer veza nije eksplicitna.
Good example
| 1 | // src/lib/legacy-text-processor.ts |
| 2 | import './polyfills/string-replace-all'; // Explicitly coupled to the consumer |
| 3 | import legacyLib from 'legacy-text-processor'; |
| 4 |
|
| 5 | export default legacyLib; |
| 6 |
|
| 7 | // src/utils.ts |
| 8 | import legacyLib from '@/lib/legacy-text-processor'; |
| 9 |
|
| 10 | export const processText = (text: string) => { |
| 11 | return legacyLib.format(text); |
| 12 | }; |
Explanation (EN)
The library and its required polyfill are wrapped in a single module. This makes it clear why the polyfill exists and ensures it is only loaded when the library is actually used. If the library is deleted, the polyfill goes with it.
Objašnjenje (HR)
Biblioteka i potreban polyfill su omotani u jedan modul. Ovo jasno pokazuje zašto polyfill postoji i osigurava da se učita samo kada se biblioteka stvarno koristi. Ako se biblioteka obriše, briše se i polyfill.
Notes (EN)
This pattern effectively implements the Facade pattern for external dependencies that require environment patching.
Bilješke (HR)
Ovaj obrazac efektivno implementira Facade uzorak za vanjske zavisnosti koje zahtijevaju patchiranje okoline.