Javascript 带有常量路径变量的reactjs动态导入
在使用reactjs动态导入时,我遇到了一个奇怪的问题。假设我有一个组件,它的名称是Javascript 带有常量路径变量的reactjs动态导入,javascript,reactjs,webpack,dynamic-import,Javascript,Reactjs,Webpack,Dynamic Import,在使用reactjs动态导入时,我遇到了一个奇怪的问题。假设我有一个组件,它的名称是ComponentA,它的路径类似于myComponents/ComponentA。现在,当我像下面的代码一样动态导入它时,它会工作得很好: Promise.all( [ import('myComponents/ComponentA'), // other imports ] ).then(....); 但如果我在常量变量
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(....);
如果您对正在发生的事情有任何想法,我们将不胜感激。也许可以尝试以下新的ES6语法:
const PATH = 'myComponents/ComponentA';
Promise.all(
[
import(`${PATH}`), // try pass it like this
// other imports
]
).then(....);
您至少需要有一个初始文本文件夹字符串(无变量)来限制可以加载的模块,因为它将绑定所有可能的文件 这是一个网页的限制。详情请参阅
很遗憾,除了文字,它不能识别
const
。你试过反勾号吗?我们可以在如下空间中使用import(“${PATH}”)
(在评论中围绕${PATH}的倒勾不能这样做)很抱歉我的回复太晚,但这也不起作用:(.使模块路径相对。你是否找到了解决方法?@MikeK,这是很久以前的事了,我没有找到解决方法。我记得我找到了一种实现我主要目标的方法。不幸的是,因为这是一个很长的过程,现在我与vuejs一起工作,我什么都不记得了:(。