In-depth
Why Dynamic Imports
Understanding why dynamic imports are important for tree-shaking.
Static imports at the top of the file are resolved before any conditionals. Use dynamic import() inside the handler to ensure server code is only loaded during prerender.
The problem with static imports
// ❌ Static import - bundled regardless of conditional
import { Server } from '~/server/data'
usePrerenderData('key', async () => {
return Server.getData() // Server already bundled!
})
With a static import, Server is included in the client bundle even though the handler will be removed by DCE. The import statement is resolved independently of the conditional wrapper.
The solution: dynamic imports
// ✅ Dynamic import - tree-shaken from client
usePrerenderData('key', async () => {
const { Server } = await import('~/server/data')
return Server.getData()
})
With a dynamic import inside the handler, the import() call is part of the handler's code path. When DCE removes the handler from the client bundle, the dynamic import is removed along with it — ensuring no server code leaks into the client.