Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created June 11, 2021 16:13
Show Gist options
  • Save itsMapleLeaf/ca2e411e4bd0f804ab4de01ca3a8cebf to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/ca2e411e4bd0f804ab4de01ca3a8cebf to your computer and use it in GitHub Desktop.
lazyNamed - React.lazy but for named exports
import * as React from 'react'
export function lazyNamed<
Name extends string,
Component extends React.ComponentType<unknown>
>(
loader: () => Promise<Record<Name, Component>>
name: Name,
): React.LazyExoticComponent<Component> {
return React.lazy(() => loader().then((mod) => ({ default: mod[name] })))
}
// example
const PostPage = lazyNamed(() => import("../post"), "PostPage")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment