Using es6 imports, you can do this:
import { MyComponent } from "../path/to/components.js";
export default function () {
return <MyComponent/>;
}
Can I do it with React.lazy
too?
const { MyComponent } = lazy(() => import("../path/to/components.js"));
I get the following error, but I'm not sure if it's related to this or some other bug I have:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined
Benefits of Lazy loading React componentsLoad the minimal code to the browser that will render a page. Load additional small chunks of code when needed. By loading less JavaScript code to the browser, that will default to better performance and better TTI results.
React. lazy takes a function that must call a dynamic import() . This must return a Promise which resolves to a module with a default export containing a React component.
Lazy Loading on route level with React Router is a powerful feature. Usually a client-side rendered React applications comes as one bundle from a web server. However, when enabling lazy loading, the bundle is split into smaller bundles.
Here is how I did it when I faced this problem with FontAwesome:
const FontAwesomeIcon = React.lazy(()=> import('@fortawesome/react-fontawesome').then(module=>({default:module.FontAwesomeIcon})))
You can if you use react-lazily.
import { lazily } from 'react-lazily';
const { MyComponent } = lazily(() => import("../path/to/components.js"));
It also allows importing more than one component:
const { MyComponent, MyOtherComponent, SomeOtherComponent } = lazily(
() => import("../path/to/components.js")
);
See this answer for more options.
React.lazy
currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components.
// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));
More info: https://reactjs.org/docs/code-splitting.html#named-exports
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With