3

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?

Seneca
  • 2,392
  • 2
  • 18
  • 33

2 Answers2

2

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.

fhelwanger
  • 465
  • 4
  • 9
  • Thanks, this solves the problem for now. Syntax is less atrocious than the require.ensure callback hell ;) – Seneca Nov 11 '15 at 07:58
  • 1
    this doesn't work for isomorphic apps though. the require('bundle?lazy!') blows up... :( – Ben Feb 19 '16 at 03:17
  • any thoughts on why webpack wont even generate chunks based on require.ensure statements. – jasan Sep 29 '16 at 04:41
  • Take a look here: https://webpack.github.io/docs/context.html#context-module. Webpack will generate chunks on require.ensure, but if it's a dynamic require, all files that can match that require will end up in the same chunk – fhelwanger Sep 29 '16 at 11:30
0

getComponent expects a function, you could try:

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