React Router Webpack 异步块加载

React Router Webpack async chunk loading

我有一个路由组件,我想用 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 有什么问题吗?

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

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

我想你可以尝试使用 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