1
我想異步地根據不同的用戶類型能夠加載反應的組分。例如,當用戶A圍繞應用程序導航時,他們的一組組件通過異步加載。然後,當用戶B使用應用程序時,他們收到了另一組通過異步加載的組件。如何基於不同的服務器端狀態異步加載React組件?
在我使用的陣營路由器和終極版的時刻。我也用的WebPack創建組件塊,其負載異步這樣的:
<Route
path="/"
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require('./app/App.jsx').default);
}, 'App');
}}
>
但是當我嘗試擴大這種動態加載組件這是行不通的。我創建對象的數組它包含了所有我想要加載組件...
{
components: [
{
id: 0,
name: 'Dashboard',
src: './dashboard/Dashboard.jsx',
indexRoute: true,
path: '/',
},
{
id: 1,
name: 'Quote',
src: './quote/Quote.jsx',
indexRoute: false,
path: '/quote',
},
],
}
然後我用地圖來創建這些組件的每一個路線...
const routes = components.map((component) => {
if (component.indexRoute) {
return (
<IndexRoute
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require(component.src).default);
}, component.name);
}}
key={component.id}
/>
);
}
return (
<Route
path={component.path}
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require(component.src).default);
}, component.name);
}}
key={component.id}
/>
);
});
但是,當我插入我創建路由到主路...
<Route
path="/"
getComponent={(location, callback) => {
require.ensure([], (require) => {
callback(null, require('./app/App.jsx').default);
}, 'App');
}}
>
{routes}
</Route>
我得到以下錯誤:
Uncaught TypeError: __webpack_require__(...).ensure is not a function
和警告:
require function is used in a way in which dependencies cannot be statically extracted
我相信這是因爲的WebPack需要知道什麼豆腐塊它在構建時編譯?這是問題,有沒有辦法解決這個問題?甚至更好的解決方案?
感謝
看看https://webpack.github.io/docs/code-splitting.html我認爲require.ensure()只同步工作,您可能需要使用AMD。 – r0dney
感謝info @ r0dney :) –