Search code examples
angularlazy-loadingangular-routingangular-lazyloading

Angular Lazy loading: loadChildren different behaviours


Guys i have an angular application with lazy loading enabled and below modules.

CoreModule, (import in app module)
SharedModule, (imported in each module)
ProjectsModule,
AuthModule

And this is my app routing module:

    { path: "",             redirectTo: "auth/sign-in", pathMatch: "full" },
// { path: "auth",      loadChildren: () => AuthModule }, // Bundled in main js file
{ path: "auth",         loadChildren: () => import("@core/auth/auth.module").then(p => p.AuthModule) },
{ path: "projects",     loadChildren: () => import("@projects/projects.module").then(p => p.ProjectsModule) }

when using dynamic import syntax in root app routing module the javascript bundles fetched in browser are below ones: (refreshing /auth/sign-in)

  • core-auth-auth-module.js
  • default~core-auth-auth-module~projects-projects-module.js
  • projects-projects-module.js (Preloading)

1- So what exactly are modules 1 and 2?

Then when i'm using function syntax on loadchildren first 2 modules don't get load in browser.

2- What's the difference?


Solution

  • The difference is that in case of using import keyword your modules are loaded lazily while loadChildren: () => AuthModule syntax will bundle AuthModule in main js file.

    - So what exactly are modules 1 and 2?

    You told Angular(webpack) to lazy load AuthModule by using import keyword. Webpack noticed this instruction and created dedicated lazy chunk with a name based on module path:

    import("@core/auth/auth.module")
                   ||
                   \/
          core-auth-auth-module.js chunk
    

    So, the first chunk is where your AuthModule resides.

    But Angular CLI uses webpack under the hood and it does some magic behind the scene with the help of SplitChunksPluginref.

    This webpack plugin tries to minimize duplication in your code and extract additional bundles from lazy modules.

    default~core-auth-auth-module~projects-projects-module.js
                    ||                        ||
                    \/                        \/
                AuthModule                   ProjectsModule
    

    This chunk contains common code shared between AuthModule and ProjectsModule.

    You can also dig deeper for details in my article: