admin管理员组

文章数量:1410724

I've seen that we can dynamically import default ponents using:

const MyComponent = React.lazy(() => import('./myPath'));

We can render it just by using <MyComponent/>. To my understanding this method only allows for the importing of default ponents from the specified path.

My question is: How can we dynamically import other ponents or functions that are exported from myPath (non default)?

I've seen that we can dynamically import default ponents using:

const MyComponent = React.lazy(() => import('./myPath'));

We can render it just by using <MyComponent/>. To my understanding this method only allows for the importing of default ponents from the specified path.

My question is: How can we dynamically import other ponents or functions that are exported from myPath (non default)?

Share asked Apr 2, 2023 at 11:31 Abhinand ShibuAbhinand Shibu 411 silver badge7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

React.lazy currently supports only default exports. A suggested solution from the docs is:

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 ponents.

For example

// 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"));

Another solution is some added boilerplate like below. This way, there is no need for an intermediary ponent:

const MyComponent = React.lazy(() =>
  import('./MyComponent').then((module) => ({ default: module.MyComponent }))
)

Alternately, you can use react-lazily like so:

const { MyComponent } = lazily(() => import('./MyComponent'))

本文标签: javascriptReactDynamically Import NonDefault Component or FunctionStack Overflow