Reputation: 687
In react router v3 i have implemented the code splitting using System.import
, Now i want to upgrade my app to react-router-v4 but the problem is that i am unable to split my code.
My
routes.js
file
function errorLoading(error) {
throw new Error(`Dynamic page loading failed: ${error}`);
}
function loadRoute(cb) {
return module => cb(null, module.default);
}
module.exports = {
path: '/',
indexRoute: {
getComponent(location, cb) {
System.import('../pages/IndexPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
childRoutes: [{
path: 'notifications',
indexRoute: {
getComponent(location, cb) {
System.import('../pages/NotificationPage')
.then(loadRoute(cb))
.catch(errorLoading);
}
},
}]
};
and then i just imported the routes in my index.js
file and rendered them to rootNode like
ReactDOM.render(
<AppContainer>
<ApolloProvider store={store} client={client}>
<Router
history={browserHistory}
routes={routes}
/>
</ApolloProvider>
</AppContainer>,
rootNode
);
Upvotes: 1
Views: 1078
Reputation: 687
Did it by simply adding routes like
<Route
name="landing"
path="/"
getComponent={
(_, cb) => import('./pages/LandingPage/LandingPage' /* webpackChunkName: 'landing' */)
.then((module) => cb(null, module.default))
.catch((error) => cb(error, null))
}
</Route>
Never forget to use the CommonsChunkPlugin
in your webpack.js
Upvotes: 0
Reputation: 1815
Check out react-async-component. It has worked great for me on my hapi-react-hot-loader-example
import {asyncComponent} from 'react-async-component';
export default asyncComponent({
name: 'AboutAsync',
serverMode: 'resolve',
resolve: () => import(/* webpackChunkName: "About" */ './About'),
});
In the Router:
<Route
path="/about"
component={AboutAsync}
/>
Upvotes: 2
Reputation: 21
If you can use ES6 dynamic imports, you could go for react-loadable and implement code-splitting this way:
export const AsyncComponent = Loadable({
loader: () => import(/* webpackChunkName: "name" */ 'path/to/Component'),
loading: () => null
})
// ...
<Route path='some/path' component={AsyncComponent} />
Upvotes: 0