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.
I implemented code splitting same way. Separate modules js files are build. So webpack build is successfully completed.
Now when i load index page. It loads but when i open new page. New page module is loaded dynamic successful.
But issue it that new js file that loaded, that component is not rendered. It does not show any error also.
<Route path="connections" getComponent={ (location, cb) => { if (__SERVER__) { Promise.all('./containers/Connections/Connections').then(loadRoute(cb)).catch(errorLoading); } else { // System.import('./containers/Connections/Connections').then(loadRoute(cb)).catch(errorLoading); require.ensure([], (require) => cb(null, require('./containers/Connections/Connections').default), 'Directory'); } } } />
this module is not rendered