0

I want to achieve code splitting of every main route so every page will have its own file (along with its subcomponents), for example I have a main render function with Route components that points to containers:

    <Route path={`path1`} component={foo.container} />
    <Route path={`path2`} component={bar.container} />

Each container looks something like this:

const mapDispatchToProps = {
... actions etc ...
}

const mapStateToProps = (state) => ({
... selectors etc ...
})

const withConnect = connect(mapStateToProps, mapDispatchToProps);

export default compose(withConnect)(MyComponent);

I tried to wrap a container and reference that in the route but it didn't work:

export default Loadable({
  loader: () => import('./MyContainer'),
  loading() {
    return (<div>Loading...</div>)
  },
});

So what am supposed to wrap then?

shinzou
  • 5,850
  • 10
  • 60
  • 124
  • 1
    check your .babelrc file and see if you are using plugin syntax-dynamic-import. As your dynamic import in react-loadable – Mohit Tilwani Aug 08 '18 at 11:51

1 Answers1

1

Here is a simplified example how to achieve code splitting with react-router and react-loadable:

MyPage.jsx - the page what you want to generate in a separate file

import React from 'react';

const MyPage = () => (
    <div>My page</div>
);

export default MyPage;

LoadableMyPage.jsx - wrapper to make your page loadable

import React from 'react';
import Loadable from 'react-loadable';

const LoadableMyPage = Loadable({
    loader: () => import('./MyPage'),
    loading: () => <div>Loading...</div>,
});

const LoadableMyPage = () => (
    <LoadableMyPage />
);

export default LoadableMyPage;

Router.jsx

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import LoadableMyPage from './LoadableMyPage';

const Router = () => (
    <Switch>
        <Route path="/" exact component={LoadableMyPage} />
        ...
    </Switch>
);

As @Mohit Tilwani mentioned, the dynamic import plugin is required because it's currently in stage-3 and not part yet of the ECMAScript.

https://github.com/tc39/proposal-dynamic-import

I started working on my own React boilerplate where I implemented the same code splitting. Do not hesitate to check it if you got stucked.

https://github.com/peetya/react-boilerplate

peetya
  • 3,578
  • 2
  • 16
  • 30
  • I have containers for each of the routes, the containers do the connect with the store with all the relevant selectors and reducers. How do you use them with this? – shinzou Sep 05 '18 at 11:59
  • Also you have `const LoadableMyPage` twice, I assume the second one should have a different name. – shinzou Sep 05 '18 at 12:09
  • How do you check if it does anything? – shinzou Sep 05 '18 at 12:26