Code splitting and dynamic loading in Webpack 4 with react loadable

351 views Asked by At

So I have a webpack 4 react app that has 2 parts:

  • Login component
  • Rest of the app

My routes.js looks like this:

import React from 'react';
import Home from 'Home';

....

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

.....

render() {
        if (!this.loggedIn) {
            return (
                <LoadableLoginComponent />
            );
        }

        return (
            <Home />
        );
    }

My webpack generates 2 js files bundle.min.js and 0.min.js

My assumption was that by default if the user is not logged in only the login component will load with 0.min.js and if user is logged in, the rest of the app will load but I see both bundle.min.js and 0.min.js being loaded.

1

There are 1 answers

0
Shawn Andrews On

If you have an if statement (!this.loggedIn) in the non-login bundle that has the possibility of rendering the login component, then the login component will be included in your non-login bundle. This is because the entry point for your non-login bundle searches all the possible code paths and files it might need to use and bundles them together, even if your if statement always fails and never uses the Login component.