React Router Webpack异步块加载

时间:2015-11-10 10:02:08

标签: webpack react-router

我有一个Route Component,我想用webpack加载异步:

<Route path="dashboard" getComponent={(location, cb) => {
  require.ensure([], (require) => {
    cb(null, require('./Containers/Dashboard'));
  });
}}>

如果您有许多需要异步块加载的其他路由,这是很多样板文件。所以我想,让我们把它重构成一个辅助方法:

const loadContainerAsync = route => (location, cb) => {
  require.ensure([], (require) => {
    cb(null, require('../Containers/' + route));
 });
};

// much 'nicer syntax'
<Route path="dashboard" getComponent={loadContainerAsync('Dashboard')} />

显然,当我查看firefox-devtools中的网络选项卡时,loadContainerAsync函数的行为无法正常运行。知道我的函数loadContainerAsync会出现什么问题吗?

2 个答案:

答案 0 :(得分:2)

我认为您可以尝试使用bundle-loader

const loadContainerAsync = bundle => (location, cb) => {
  bundle(component => {
    cb(null, component);
  });
};

// 'not so nice syntax', but better than first option :)
<Route path="dashboard" getComponent={loadContainerAsync(require('bundle?lazy!../containers/Dashboard'))} />

别忘了$ npm install bundle-loader --save-dev

答案 1 :(得分:0)

getComponent需要一个函数,你可以尝试:

StreamedContent