question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Setting up code splitting in Webpack and React Router

See original GitHub issue

I’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:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
mantou132commented, Dec 19, 2016

I have the same problem; And can not be 100% reproduction I use browserHistory

1reaction
janvennemanncommented, May 9, 2016

If you are comfortable with using Webpack 2 Beta you can try System.import() instead of require.ensure() to setup code splitting. Your route definition could look something like this:

import Site from './containers/Site'

function errorLoading(err) {
  console.error('Dynamic page loading failed', err);
}

return {
  component: Site,
  childRoutes: [
    {
      path: 'profile',
      getComponent: (location, cb) => {
        System.import('./attendee/containers/Profile')
          .then(function(m) {
            cb(null, m.default)
          })
          .catch(errorLoading);
      }
    }
  ]
}

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Code-Splitting - React
Code -Splitting is a feature supported by bundlers like Webpack, Rollup and Browserify (via factor-bundle) which can create multiple bundles that can be ......
Read more >
Webpack (v4) Code Splitting using SplitChunksPlugin - Medium
Introduction to code splitting in Webpack v4 and with `import()` function → lazy loading routes in React using React Router v4. Webpack 4...
Read more >
How I set up code-splitting on an existing React app with ...
If you are starting a new project, consider using a framework that gives you code-splitting “for free” and wraps Webpack and routing setup...
Read more >
Code Splitting with React, React.lazy, and React Router - ui.dev
In this post you'll learn how to increase the performance of your React application by adding code splitting with React.lazy and React ......
Read more >
Code splitting and preloading React routes with Webpack
An introduction to setting up code splitting on React routes using Webpack with several ways of managing preloading.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found