javascriptreactjswebpackcode-splittingasync-components

Code Splitting with react-loadable gives Error : Cannot find module "."


I'm using react-loadable v4.0.4 and webpack v3.5.1.

Here is my code,

import Dashboard from '../../scenes/dashboard/dashboard';    
import ReactLoadable from 'react-loadable';
...

const yoPath = 'src/components/scenes/dashboard/dashboard';

const DashboardWrap = ReactLoadable({
    loading: Dashboard,
    loader: () => {
        return new Promise((resolve, reject) =>
            require.ensure(
               [],
               (require) =>  resolve(require(yoPath)),
               (error) => reject(error),
               'dashboardChunk'
            )
         )
    }
});

And using react-router-dom v4.1.2, I've set Route as follows,

<Switch>
...
<Route exact path='/dashboard' component={DashboardWrap} />
...
</Switch>

I'm able to build the chunks for the respective component with the name dashboardChunk.

But while loading that component I'm getting the issues as follows.

enter image description here

In the console,

enter image description here

And the chunkfile,

enter image description here

Please let me know if I'm doing anything wrong.


Solution

  • I basically wanted to do code splitting, for that I've just done the following and it works fine.

    I've created a common component(wrapper component) as follows,

    import React, { Component } from 'react';
    
    class Async extends Component {
        componentWillMount = () => {
            this.props.load.then((Component) => {
                this.Component = Component
                this.forceUpdate();
            });
        }
    
        render = () => (
            this.Component ? <this.Component.default /> : null
        )
    }
    
    export default Async;
    

    Then I've used above component as follows,

    export const AniDemo = () => <Async load={import(/* webpackChunkName: "aniDemoChunk" */ "../../scenes/ani-demo/AniDemo.js")} />
    export const Dashboard = () => <Async load={import(/* webpackChunkName: "dashboardChunk" */ "../../scenes/dashboard/Dashboard.js")} />
    

    And using the above, I've made the changes in route as follows,

    <Route exact path="/ani-demo" component={AniDemo} />
    <Route exact path="/dashboard" component={Dashboard} />
    

    With the help of the above changes that I made, I'm able to create chunks properly with the names that I've mentioned in the comments inside import statements ie aniDemoChunk.js and dashboardChunk.js respectively.

    And these chunks load only when the respective component is called ie aniDemoChunk.js is loaded on browser only when AniDemo component is called or requested. Similarly for the Dashboard component respectively.

    Note: If anyone is getting error re:Unexpected token import. So to support import() syntax just replace import to System.import() or else use babel-plugin-syntax-dynamic-import.