Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Webpack async chunk loading

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')} />

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?

like image 449
Seneca Avatar asked Apr 12 '26 15:04

Seneca


1 Answers

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'))} />

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

like image 151
fhelwanger Avatar answered Apr 14 '26 10:04

fhelwanger