| 1 | --- |
| 2 | title: Conditional Module Loading |
| 3 | impact: HIGH |
| 4 | impactDescription: loads large data only when needed |
| 5 | tags: bundle, conditional-loading, lazy-loading |
| 6 | --- |
| 7 | |
| 8 | ## Conditional Module Loading |
| 9 | |
| 10 | Load large data or modules only when a feature is activated. |
| 11 | |
| 12 | **Example (lazy-load animation frames):** |
| 13 | |
| 14 | ```tsx |
| 15 | function AnimationPlayer({ |
| 16 | enabled, |
| 17 | setEnabled, |
| 18 | }: { |
| 19 | enabled: boolean |
| 20 | setEnabled: React |
| 21 | }) { |
| 22 | const [frames, |
| 23 | |
| 24 | useEffect(() => |
| 25 | if (enabled && |
| 26 | import("./animation-frames.js") |
| 27 | .then((mod) |
| 28 | .catch(() => |
| 29 | } |
| 30 | }, [enabled, |
| 31 | |
| 32 | if (!frames) |
| 33 | return <Canvas |
| 34 | } |
| 35 | ``` |
| 36 | |
| 37 | The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. |