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 require
s 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.
Just, for the record: I wasn't able to implement this several reasons:
System.import('/my/path/here')
. This is conflicting with it's documentation, which seems to imply you can do this; I think you have to provide at least part of the path for it to make guesses about all the files you would like to include.So maybe I did something wrong, but I, at least, was not able to get this to work through this really really nice-looking abstraction.