Skip to content

Instantly share code, notes, and snippets.

@vasanthk
Forked from mxstbr/idea.md
Created June 2, 2017 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasanthk/0aa8dcaf77a642d0534c52c215bb60f0 to your computer and use it in GitHub Desktop.
Save vasanthk/0aa8dcaf77a642d0534c52c215bb60f0 to your computer and use it in GitHub Desktop.
Code splitting react-router routes with webpack 2

NOTE: Sokra confirmed I had a misunderstanding, Webpack is still a static build tool and the below won't work. It's still a nice concept though...

With webpack 1, code splitting react-router routes is quite tedious. It requires us to repeat the getComponent function over and over again. (See here for an explanation how it works with webpack 1)

Example:

<Router history={history}>
  <Route
    path="/"
    getComponent={(location, callback) => {
      require.ensure([], function (require) {
        callback(null, require('./HomePage.jsx'));
      });
    }}
  />
  <Route
    path="/about"
    getComponent={(location, callback) => {
      require.ensure([], function (require) {
        callback(null, require('./AboutPage.jsx'));
      });
    }}
  />
</Router>

The getComponent function is almost the same across all routes, that's not very DRY. The problem is that with webpack v1, it needed the requires as static strings because it analyses the code before evaluation, and it needs to somehow determine there which modules should go into seperate chunks.

With webpack 2 though, we're getting System.import and dynamic expressions! (src) This'll make code splitting react-router routes so much easier. Imagine a component like this:

class Page extends React.Component {
  render() {
    <Route
      path={this.props.path}
      getComponent={(location, callback) => {
        System.import(this.props.component)
          .then((component) => {
            callback(null, component);
          });
      }
  }
}

Used like this:

<Router history={history}>
  <Page path="/about" component="./AboutPage.jsx" />
</Router>

And all of these <Page>s are now in seperate chunks! Code splitting react-router routes: easy with webpack 2.

Note: This is just an idea, none of the new code above is tested.

@lonif
Copy link

lonif commented Jun 16, 2017

salut
comment vous allez hi how are you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment