Skip to content

Instantly share code, notes, and snippets.

@bever1337
Last active September 30, 2022 17:06
Show Gist options
  • Save bever1337/fedcb311d437460fd4822036b73690c6 to your computer and use it in GitHub Desktop.
Save bever1337/fedcb311d437460fd4822036b73690c6 to your computer and use it in GitHub Desktop.
A little glue to support named exports with React.lazy
// Returns all named exports as though they were dynamic default exports
// https://reactjs.org/docs/code-splitting.html#named-exports
import { lazy } from 'react';
/**
* @function lazyNamedExport
* @param {function} dynamicImportCallback
* @param {string} exportKey
* @description Returns all named exports as though they were dynamic default exports
* @example
* import { lazy, Suspense } from 'react';
* const LazyComponent = lazyNamedExport(() => import('./foo'), 'foo');
* function Component() {
* return (
* <Suspense fallback={<p>loading...</p>}>
* <LazyComponent />
* </Suspense>
* );
* }
*/
const lazyNamedExport = (dynamicImportCallback, exportKey) =>
lazy(() =>
dynamicImportCallback().then(({ [exportKey]: lazyComponent }) => ({
default: lazyComponent,
}))
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment