💡 This package is now a part of
@darkobits/react-kit
. Check it out there!
- Lazily import React components that are defined using named exports.
- Supports destructuring syntax, including nesting.
- 100% type-safe.
$ npm install @darkobits/react-lazy-named
Assuming we have a file Components.tsx
that exports 2 React components and some other value:
Components.tsx
import React from 'react';
export const Foo = () => {
return (
<div>Foo</div>
)
};
export const Bar = () => {
return (
<div>Bar</div>
);
}
export const Baz = false;
Then, in another file, we can lazily import these components thusly:
App.tsx
import { lazy } from '@darkobits/react-lazy-named';
import React from 'react';
// Foo, Bar are correctly typed as lazy React components.
const { Foo, Bar } = lazy(async () => import('./Components.tsx'));
// Type error.
const { Baz } = lazy(async () => import('./Components.tsx'));
export const App = () => {
return (
<Foo />
<Bar />
)
}
This module attaches a static preload
method to components that can be invoked to optimistically
pre-load a component. This method returns a Promise
that will resolve when the component has loaded.
import { lazy } from '@darkobits/react-lazy-named';
const { Foo } = lazy(async () => import('./Components.tsx'));
await Foo.preload();
- When using this (or other solutions) to circumvent the default export requirement, tree-shaking will not work on the imported module. In most cases, this should not be an issue.
- Inspired by this discussion on the topic.