最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React - Dynamically Import Non-Default Component or Function - Stack Overflow

programmeradmin7浏览0评论

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'))
发布评论

评论列表(0)

  1. 暂无评论