React router webpack download async chunk

I have a route component that I want to download async with webpack:

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

These are many templates if you have many other routes that require asynchronous loading. So I thought, let me reorganize 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')} /> 

Apparently, when I look at the network tab in firefox-devtools, the behavior of the loadContainerAsync function does not work correctly. Any idea what could be wrong with my loadContainerAsync function?

+3
source share
2 answers

I think you can try using 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'))} /> 

Don't forget $ npm install bundle-loader --save-dev .

+2
source

getComponent expects a function, you can try:

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

All Articles