reactjs动态导入与常量路径变量

时间:2017-12-31 11:32:40

标签: javascript reactjs webpack dynamic-import

使用reactjs动态导入时遇到了一个奇怪的问题。假设我有一个名为ComponentA的组件,它的路径就像myComponents/ComponentA。现在,当我像下面的代码一样动态导入它时,它会运行良好:

Promise.all(
        [
            import('myComponents/ComponentA'),
            // other imports
        ]
    ).then(....);

但是如果我在一个常量变量中定义我的组件路径,如下所示:

//before definition of my current component
const PATH = 'myComponents/ComponentA';
.
.
.
// some where in my component class
Promise.all(
    [
        import(PATH),
        // other imports
    ]
).then(....);

它会给我一个这样的错误:

  

错误:找不到模块'myComponents / ComponentA'。

有时候如果我只是在我的PATH变量中添加一个空字符串就可以解决问题,有时则不会。

//before definition of my current component
const PATH = 'myComponents/ComponentA';
.
.
.
// some where in my component class
Promise.all(
    [
       import(''+PATH), // some times by adding empty string, problem would be solved
       // other imports
    ]
 ).then(....);

任何有关正在发生的事情的想法都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

也许尝试这种新的ES6语法:

const PATH = 'myComponents/ComponentA';
Promise.all(
    [
       import(`${PATH}`), // try pass it like this
       // other imports
    ]
 ).then(....);

答案 1 :(得分:0)

您至少必须有一个初始的文字文件夹字符串(无变量)来限制可以加载的模块,因为它将捆绑所有可能的文件。

这是webpack的限制。有关详细信息,请参见https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

真可惜,除了文字之外,我无法识别const

相关问题