[英]reactjs dynamic import with constant path variable
我在使用 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(....);
任何關於正在發生的事情的想法將不勝感激。
也許試試這個新的 ES6 語法:
const PATH = 'myComponents/ComponentA';
Promise.all(
[
import(`${PATH}`), // try pass it like this
// other imports
]
).then(....);
您至少必須有一個初始文字文件夾字符串(無變量)來限制可以加載的模塊,因為它將捆綁所有可能的文件。
這是 webpack 的一個限制。 詳情見https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import
這確實是不承認的,可惜const
比文字等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.