Setting up code separation in Webpack and React.js

I am trying to customize code splitting / splitting in my application by route using require.ensure . So here is my route:

 <Route path="profile" getComponent={(location, cb) => {require.ensure( [], (require) => { cb(null, require('attendee/containers/Profile/').default) }, 'attendee')}} /> 

Here are the relevant lines from my webpack configuration:

 const PATHS = { app: path.join(__dirname, '../src'), build: path.join(__dirname, '../dist'), }; const common = { entry: [ PATHS.app, ], output: { path: PATHS.build, publicPath: PATHS.build + '/', filename: '[name].js', chunkFilename: '[name].js', sourceMapFilename: '[name].js.map' }, target: 'web', devtool: 'cheap-module-eval-source-map', entry: [ 'bootstrap-loader', 'webpack-hot-middleware/client', './src/index', ], output: { publicPath: '/dist/', }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"development"', }, __DEVELOPMENT__: true, }), new ExtractTextPlugin('main.css'), new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.ProvidePlugin({ jQuery: 'jquery', }), ], 

When I go to the page on the route, I see in the logs that the requested fragment is loading. However, the page does not load.

And I see the following stack trace in the console:

 Uncaught TypeError: Cannot read property 'call' of undefined t @ main.js:10 (anonymous function) @ main.js:44637 window.webpackJsonp @ main.js:40 (anonymous function) @ attendee.js:1 

The line she complains about is this:

 return e[n].call(o.exports, o, o.exports, t) 

The second line ((anonymous function) @ main.js: 44637) is essentially this:

 require('attendee/containers/Profile/').default 

Note that if I do console.log(require('./attendee/containers/Profile/').default) , I get the function as output, so I'm not sure why this is undefined. And of course, when I do this, the code works, but no more.

So, I'm doing something wrong with require . Any idea what it is?

BTW I use hash history in this project - could this be the culprit?

Update:

Also tried the package loader, as in this answer . The same result.

+6
source share
1 answer

you're almost there! Try this: you need to predefine the array of module dependencies in the first argument of require.ensure instead of [] , explicitly set it to ['attendee/containers/Profile']

 (location, cb) => { require.ensure(['attendee/containers/Profile'], (require) => { cb(null, require('attendee/containers/Profile').default) }) } 
0
source

All Articles