Skip to content

Instantly share code, notes, and snippets.

@o-az
Created December 24, 2021 05:09
Show Gist options
  • Save o-az/6375c1131f792710e4a852c54b1ddd59 to your computer and use it in GitHub Desktop.
Save o-az/6375c1131f792710e4a852c54b1ddd59 to your computer and use it in GitHub Desktop.
Lets you React.lazy import named exports
import * as React from 'react'
function lazyImport<
T extends React.ComponentType<any>,
I extends { [K2 in K]: T },
K extends keyof I
>(factory: () => Promise<I>, name: K): I {
return Object.create({
[name]: React.lazy(() =>
factory().then(module => ({ default: module[name] }))
),
})
}
// Usage
const { Home } = lazyImport(() => import('./Home.component.tsx'), 'Home')
// Credit: https://github.com/JoseLion
// https://github.com/facebook/react/issues/14603#issuecomment-726551598
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment