React Router Webpack异步块加载

问题描述 投票:3回答:2

我有一个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有什么问题吗?

webpack react-router
2个回答
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


0
投票

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

const loadContainerAsync = route => (location, cb) => {
  return (location, cb) => {
    require.ensure([], (require) => {
      cb(null, require('../Containers/' + route));
    });
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.