React路由器Webpack异步代码块加载

3

我有一个路由组件,我想使用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个回答

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

谢谢,这暂时解决了问题。语法比 require.ensure 回调地狱要好得多 ;) - Seneca
1
这对于同构应用程序不起作用。 require('bundle?lazy!')会崩溃... :( - Ben
你对于为什么Webpack甚至不会根据require.ensure语句生成代码块有什么想法吗? - jasan
请看这里:https://webpack.github.io/docs/context.html#context-module。Webpack将在require.ensure上生成块,但如果是动态require,则所有可以匹配该require的文件都将最终放入同一个块中。 - fhelwanger

0

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

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

抱歉,我忽略了你已经将它封装在一个方法中(该死的ES6 :) - Jack van der Eijk
Np :) 必须热爱 ES6 ;p - Seneca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接