2017-03-16 49 views
0

我剛開始使用的WebPack,我使用的是動態頁面加載反應的路由器,並且要動態導入我的文件,但得到的的WebPack這樣的警告:weback 2未能與反應路由器動態路徑導入文件

警告在./apps/pages/routes.js 35:6-44臨界依賴性:一個依賴的請求是一個表達式

這裏是我的代碼的示例:

const routes = { 
 
    component: App, 
 
    childRoutes: [ 
 
    { 
 
     path: '/', 
 
     getComponent (location, cb) { 
 
     System.import('./Home') 
 
      .then(loadRoute(cb)) 
 
      .catch(errorLoading) 
 
     } 
 
    }, 
 
    { 
 
     path: 'about', 
 
     getComponent (location, cb) { 
 
     System.import('./About') 
 
      .then(loadRoute(cb)) 
 
      .catch(errorLoading) 
 
     } 
 
    } 
 
    ] 
 
}

這工作得很好,但是當我想用這樣的變量,使其:

const routersPaths = [ 
 
    {path: '/', filePath: './Home'}, 
 
    {path: 'about', filePath: './About'} 
 
] 
 

 
const childRoutes = routersPaths.map(childRoute => { 
 
    return { 
 
    path: childRoute.path, 
 
    getComponent (location, cb) { 
 
     System.import(childRoute.filePath) 
 
     .then(loadRoute(cb)) 
 
     .catch(errorLoading) 
 
    } 
 
    } 
 
}) 
 

 
const routes = { 
 
    component: App, 
 
    childRoutes: childRoutes 
 
}

失敗。我想知道有沒有辦法做到這一點?

回答

1

不可能使用變量作爲參數來導入。 Webpack需要知道在編譯時要包含哪些模塊,並且它不進行程序流分析,因此無法知道包含哪些模塊。在你的情況下,它可能很容易確定,但它可能會更進一步,因爲你可以在運行時隨意構建導入路徑,所以webpack根本不允許它。

有一個例外,你可以使用一個連接字符串,但將增加所有模塊與表達式匹配的管束,即使他們不使用,如圖require with expression(該規則同樣適用於進口和要求)。但是應該避免這種做法。

順便說一句,System.import is deprecated和已被替換import()(功能)。

+0

謝謝你的回答。是的,我知道串聯字符串,但這不是我想要的。所以沒有辦法動態導入組件? – Gayane

+0

不,沒有。 –