React懒加载使用命名导入

4

如何使用延迟语法导入命名导入?

在我们能够使用以下语法之前:

import { MainComponent, Component1, Component2 } from './components';

如何实现类似这样的效果(尽管这并不起作用)?:
const { MainComponent, Component1, Component2 } = React.lazy(() => import('./components'));

1
好问题。我不认为这是可能的。你应该导出一个包含所有组件的默认对象。 - Brian Le
5个回答

4

目前,React.lazy不支持命名导入:

此RFC的范围有限。它针对我们想要处理的主要用例(默认导入)进行了定位。未来的RFC可能会支持命名导入,但这超出了本RFC的范围。本RFC故意非常有限。我们预计在接下来的几个月内更好地了解这个问题,并且我们可以在更好地理解后重新讨论这个问题。 reactjs/rfcs#64 (comment)


1

React不支持命名导出

这里,您可以找到如何创建中间模块的示例

这意味着每个导入都需要另一个文件。目前没有更好的语法,但我们希望将来会有。

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

0

您可以逐个导入它们 -

const ComponentName = React.lazy(() => import('./componentname'));

这正是我不想做的。不想有这么多行分离的导入。 - Murakami
我听到你说的了,但是这个语法不是我写的,这个方法现在是有效的。你可以尝试在 https://github.com/facebook/react/issues 提交一个问题。祝你好运! - Karl
如果它是一个命名导出,这将不起作用。 - Adrian Bartholomew

0
我们团队希望避免使用默认导出,因此我们在TS中编写了一个CustomLazy组件。
/**
 * Improvement on top of React.lazy() that allows lazy rendering of named imports
 * Usage:
 *
 *  -- alternative to import { primary } from './Button'
 *  const PrimaryButton = CustomLazy(() => import('./Button'),'primary');
 *
 *  -- get the default import
 *  CustomLazy(() => import('./Button'), 'default');
 *
 *  -- or
 *  CustomLazy(() => import('./Button'));
 *
 */
// eslint-disable-next-line no-restricted-imports
import { ComponentType, lazy } from 'react';

type CustomLazyProps = <T extends ComponentType<React.PropsWithChildren<any>>>(
  thenable: () => Promise<{
    [name: string]: T;
  }>,
  name?: string
) => React.LazyExoticComponent<T>;

const CustomLazy: CustomLazyProps = (resolver, name = 'default') => {
  return lazy(async () => {
    const resolved = await resolver();
    return { default: resolved[name] };
  });
};

export default CustomLazy;

-3

虽然我没有尝试过,但是类似这样的代码应该可以工作:

const { MainComponent, Component1, Component2 } = React.lazy(() => 
import('./components')).then(module => ({
    default: {
        MainComponent: module.MainComponent,
        Component1: module.Component1,
        Component2: module.Component2,
}));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接