Setting up code splitting in Webpack and React Router
See original GitHub issueI’ve gone through all parts of the documentation and went through a whole bunch of tutorials all over the web, but I’m still missing something.
I’m trying to set up chunking in my app by route, using require.ensure
. So here’s my route:
<Route path="profile"
getComponent={(location, cb) =>
{require.ensure(
[],
(require) => { cb(null, require('attendee/containers/Profile/').default) },
'attendee')}} />
Here are relevant lines from my webpack config:
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 navigate to the page in the route, I see in the logs that the required chunk does get downloaded. The page however does not load.
And I see the following stack trace in the browser 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 it 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, if I do console.log(require('./attendee/containers/Profile/').default)
, I get a function as an output, so I’m not sure why it is undefined. And of course when I do that the code works, but than there’s no chunking any more.
So I’m doing something wrong with the require
. Any idea what it is? Thanks
I asked the same question on SO with no results: http://stackoverflow.com/questions/36988975/setting-up-code-splitting-in-webpack-and-react-js
Issue Analytics
- State:
- Created 7 years ago
- Reactions:2
- Comments:5 (2 by maintainers)
I have the same problem; And can not be 100% reproduction I use browserHistory
If you are comfortable with using Webpack 2 Beta you can try
System.import()
instead ofrequire.ensure()
to setup code splitting. Your route definition could look something like this:Also take a look at this Tutorial, which pushed me into the right direction when setting up code splitting. Keep in mind that this will only work on the client side out of the box. For the time being i use another route file with the exact same routes using static imports on the server.