React的懒加载导入语句无法处理表达式。

4

所以以下动态加载代码能够正常工作:

return React.lazy(() => import("./hotels/components/" + componentName));

以下代码无法正常工作:

const path = "./hotels/components/";
return React.lazy(() => import(path + componentName));

我认为这可能与缩小器有关,因为在它正常工作的情况下,“import”会在VSCode中变成蓝色。而在它不正常工作的情况下,“import”会变成黄色。

此外,在编译无法正常工作的情况下,我会收到以下警告:

Critical dependency: the request of a dependency is an expression

有人遇到过这个问题吗?

我尝试了与这个类似的问题中提到的所有解决方法:

Webpack - 严重依赖关系:依赖项的请求是一个表达式


这个回答解决了你的问题吗?Webpack - 严重依赖:依赖项的请求是一个表达式 - Viet Dinh
@Viet Dinh 它没有起作用。 - Maxqueue
这可能会对你有帮助,请参考这里 - Eric
@Eric 是的,这个有效,谢谢。 - Maxqueue
2个回答

3
以下方法解决了错误并消除了警告。只需嵌入变量即可。
return React.lazy(() => import(`${path + componentName}`));

0
在我的TypeScript情况下,我不得不在getComponent.ts中创建一个单独的函数。
src -> Utils -> getComponent.ts

import React, { lazy } from 'react';

type Component = React.LazyExoticComponent<React.ComponentType<any>>;
const componentCache: Record<string, Component> = {};

/**
 * Retrieves a component based on a relative path from the ./src/ directory.
 *
 * @param {string} path - Relative path from the ./src/ directory.
 * @param {string} name - Component name.
 */
export default function getComponent(path: string, name: string): any {
    if (!componentCache[name]) {
        componentCache[name] = lazy(() => import(`../${path}`));
    }

    return componentCache[name];
}

我们可以这样使用它:

 {tabs.map((el, index) => (
    <Box key={index}>
        <React.Suspense fallback={<>...</>}>
            {React.createElement(
                getComponent(el.componentSrc, el.componentName)
            )}
        </React.Suspense>
    </Box>
))}

在标签中的数据

export const importerTabs: any[] = [
    {
        componentName: 'FirstCompoent',
        componentSrc: 'Pages/FirstPage/FirstCompoent',
    },
    {
        componentName: 'SecondComponent',
        componentSrc: 'Pages/SecondPage/SecondComponent',
    }
];


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