返回 AiToEarn
bundle-conditional.md
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({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
16 const [frames, setFrames] = useState<Frame[] | null>(null)
17
18 useEffect(() => {
19 if (enabled && !frames && typeof window !== 'undefined') {
20 import('./animation-frames.js')
21 .then(mod => setFrames(mod.frames))
22 .catch(() => setEnabled(false))
23 }
24 }, [enabled, frames, setEnabled])
25
26 if (!frames) return <Skeleton />
27 return <Canvas frames={frames} />
28 }
29 ```
30
31 The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
32
32 lines MARKDOWN