React Router Webpack 异步块加载 [英] React Router Webpack async chunk loading
问题描述
我有一个路由组件,我想用 webpack 异步加载它:
I have a Route Component which I want to load async with webpack:
<Route path="dashboard" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('./Containers/Dashboard'));
});
}}>
如果您有很多其他需要异步块加载的路由,那么这是很多样板文件.所以我想,让我们把它重构为一个辅助方法:
This is a lot of boilerplate if you have a lot of others routes that need async chunk loading. So I thought, let's refactor this into a helper method:
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 有什么问题吗?
Apparently when I look at the network tab in the firefox-devtools, the behavior of the loadContainerAsync function doesn't function correctly. Any idea what could be wrong with my function loadContainerAsync?
推荐答案
我想你可以尝试使用 bundle-加载器.
I think you can try using the 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
.
这篇关于React Router Webpack 异步块加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!