React.lazy wrapper that works with allows you to destruct imported module, so it will work with non default exports
npm install react-lazily


react-lazily is a simple wrapper around React.lazy (or loadable from @loadable/component) that supports named imports.
Consider a component MyComponent that is exported with a default export:
``ts`
export default MyComponent;
Per React docs, you could use React.lazy as follows:
`ts`
const MyComponent = React.lazy(() => import('./MyComponent'));
However, if the component is exported with a named export:
`ts`
export const MyComponent = ...
You would have to use React.lazy like this:
But if the component is exported with named export export const MyComponent = ... then you have to do:
`ts`
const MyComponent = React.lazy(() =>
import('./MyComponent').then((module) => ({ default: module.MyComponent }))
);
With react-lazily it becomes:
`ts`
const { MyComponent } = lazily(() => import('./MyComponent'));
See the live example: https://codesandbox.io/s/react-lazily-example-p7hyj
`ts
import React, { Suspense } from 'react';
import { lazily } from 'react-lazily';
const { MyComponent } = lazily(() => import('./MyComponent'));
const App = () => {
const [open, setOpen] = React.useReducer(() => true, false);
return (
<>
{open ? (
Full Example with @loadable/component
Don't forget to install
@loadable/component first.`ts
import React from 'react';
import { loadable } from 'react-lazily/loadable';const { MyComponent } = loadable(() => import('./MyComponent'), {
fallback:
Loading...,
});const App = () => {
const [open, setOpen] = React.useReducer(() => true, false);
return (
<>
{open ? : }
>
);
};
``- Allow for named imports in React.lazy (GitHub Issue)
- Can you deconstruct lazily loaded React components? (Stack Overflow)
- solidjs-lazily (NPM Package)