Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is webpack code splitting not working for me?

I'm using require.ensure to create split points at react-router paths. However, my build directory still only has app.js in addition to the vendor.js. I was expecting a separate js file for each path I used require.ensure.

I used require.ensure at each path like this:

<Route path= 'auth' getComponent={(nextState, callback) => {
  require.ensure([], (require) => {
    callback(null, require('containers/Authenticate/AuthenticateContainer.js').default)
  }, 'auth')
}}/>

my web pack config output for build looks like this:

output: {
  path: PATHS.build,
  filename: '/[name].[chunkhash].js',
  chunkFilename: '/[chunkhash].js'
}

Here are the gists of my route file and my webpack config file in their entirety.

UPDATE: I figured out what I was doing wrong. My project structure for containers is like so:

-app
 -containers
   -containerA.
     -containerA.js
   -containerB
     -containerB.js
   -containerC
     -containerC.js
   -index.js

The issue: I was still exporting the containers I was requiring in routes file like so: export containerB from './containerB/containerB' Removing the export in the index.js and requiring straight from the containerB.js did the trick.

like image 661
jasan Avatar asked Sep 28 '16 20:09

jasan


1 Answers

Ensure takes an argument array of modules you want to require. You need to supply the array with the module names you wish to dynamically load. In your case, provide 'containers/Authenticate/AuthenticateContainer.js' to ensure like this:

require.ensure(['containers/Authenticate/AuthenticateContainer.js'], (require) => {
      callback(null, require('containers/Authenticate/AuthenticateContainer.js').default)
    }, 'auth');
like image 66
cgatian Avatar answered Sep 27 '22 23:09

cgatian