angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Lazy loading is not working together with 'import *' syntax

Open areijngoudt opened this issue 10 years ago • 85 comments

Please provide us with the following information:

OS?

Mac OSX El Capitan

Versions.

angular-cli: 1.0.0-beta.16 node: 5.7.1 os: darwin x64

Repro steps.

Was this an app that wasn't created using the CLI? What change did you do on your code? etc. The app was not created using the CLI. When upgrading to Angular 2 I choose to use the CLI as serving and building tool

I have this route in my app.routing.ts:

const ROUTES: Routes = [
    { path: '', redirectTo: 'analyse', pathMatch: 'full' },
    { path: 'annotate', component: AnnotateComponent },
    { path: 'fraud', component: FraudComponent },
    { path: 'info',  loadChildren: 'app/info/info.module#InfoModule'  },
];```

the InfoModule should be loaded lazily when navigating to it's path. But even in de --prod build there's no seperate bundle. The InfoModule is still part of the main.bundle.js.

Note that I'm still importing the InfoModule in the app.module.ts otherwise the info route does not work at all.

areijngoudt avatar Oct 04 '16 09:10 areijngoudt

You should not import InfoModule nowhere else. Only reference in routes' loadChildren

neilhem avatar Oct 04 '16 10:10 neilhem

When ommitting the import in app.modules, an error occurrs that route info is unknown. I'm using the angular-cli webpack version btw.

areijngoudt avatar Oct 04 '16 16:10 areijngoudt

If you import your InfoModule into app.module.ts then, you will not be using LazyLoad. Your module will be compile as main part of your app.

Could you please post your info.routing.ts?

wrosb avatar Oct 05 '16 15:10 wrosb

info.routing.ts:

import { ModuleWithProviders }  from '@angular/core';
import { RouterModule } from '@angular/router';

import { InfoComponent } from './info.component';

const ROUTES = [
  { path: '', component: InfoComponent}
];
export const routing: ModuleWithProviders = RouterModule.forChild(ROUTES);

areijngoudt avatar Oct 05 '16 15:10 areijngoudt

I could not find anything unusual in your code. I recreated a sample with your code and works fine for me. Your ROUTES const should has a type def, but even without a type def, routing works fine in my test.

Try this, just as best practice: import { ModuleWithProviders } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { InfoComponent } from './info.component';

const ROUTES: Routes = [ { path: '', component: InfoComponent} ]; export const routing: ModuleWithProviders = RouterModule.forChild(ROUTES);

I'm also using angular-cli@beta16, but over ubuntu 16. Maybe you should try a clean project and test it.

wrosb avatar Oct 05 '16 19:10 wrosb

Hi all, I have the same problem. I have all the routes "inlined" in a DashboardModule file that I wish to lazyload... When I removed the import in my AppModule, my app crashed with a EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'dashboard' error message... If I add DashboardModule to my @NgModule's imports, it works as expected.

Also, ng serve --prod creates 2 sets of main.*.bundle.js and styles.*.bundle.js as expected when DashboardModule is not imported

My AppModule:

@NgModule({
    imports:      [
        BrowserModule,
        HttpModule,
        CommonModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', component: LandingpageModule},
            { path: 'dashboard', loadChildren: `app/dashboard/dashboard.module#DashboardModule`}
        ]),
        LandingpageModule,
    ],
    bootstrap:    [AppComponent],
    providers:    [
        LoggedInGuard,
        authConfigProvider,
        JwtHelper,
        AuthHttp,
        AuthService
    ],
    declarations: [AppComponent],
})
export class AppModule {}

And my DashboardModule:

@NgModule({
    imports: [
        FormsModule,
        RouterModule.forChild([{
            path: 'dashboard',
            component: DashboardComponent,
            children: [
                { path: '', component: HomeComponent,canActivate: [LoggedInGuard]},
                { path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard] },
                { path: 'billing', component: BillingComponent, canActivate: [LoggedInGuard, AdminGuard] },
                { path: 'administration', component: AdministrationComponent, canActivate: [LoggedInGuard, AdminGuard] },
            ],
            canActivate: [LoggedInGuard]
        }]),
        CommonModule,
    ],
    providers: [
        AdminGuard
    ],
    declarations: [
        HomeComponent, StatusPanelComponent,DashboardComponent,
        ProfileComponent,AdministrationComponent,BillingComponent
    ]
})
export class DashboardModule {}

Richard87 avatar Oct 06 '16 04:10 Richard87

@Richard87 you should set root path in DashboardModule as path: ''. So it will be

RouterModule.forChild([{
  path: '',
  component: DashboardComponent,
  children: [

neilhem avatar Oct 06 '16 06:10 neilhem

@neilhem Thanks! The routing works, but I still don't get lazy loading? (There are no reference to DashboardModule in AppModule except for the loadChildren string)...

Also, it doesn't seem like ng serve --prod produces 2 bundle js files (I might have been wrong earlier, it looks like 1 of them where gzipped...)

                                              Asset       Size  Chunks             Chunk Names
                       assets/fonts/FontAwesome.otf     125 kB          [emitted]
                main.ef31a7b0feb1135ed298.bundle.js     1.2 MB    0, 2  [emitted]  main
                                          inline.js    1.39 kB       2  [emitted]  inline
           styles.667c85c265538fc61bbe.bundle.js.gz    26.6 kB          [emitted]
             main.ef31a7b0feb1135ed298.bundle.js.gz     285 kB          [emitted]
                                         index.html  542 bytes          [emitted]
                                  assets/.npmignore    0 bytes          [emitted]
               assets/fonts/fontawesome-webfont.eot    76.5 kB          [emitted]
               assets/fonts/fontawesome-webfont.svg     392 kB          [emitted]
               assets/fonts/fontawesome-webfont.ttf     153 kB          [emitted]
              assets/fonts/fontawesome-webfont.woff    90.4 kB          [emitted]
             assets/fonts/fontawesome-webfont.woff2    71.9 kB          [emitted]
              styles.667c85c265538fc61bbe.bundle.js     162 kB    1, 2  [emitted]  styles

Any tips on how to troubleshoot?

Richard87 avatar Oct 06 '16 07:10 Richard87

You should not import files from other lazy modules in your lazy module

neilhem avatar Oct 06 '16 07:10 neilhem

What do you mean? Like my AuthService or AuthHttp?

Also, I only have 1 lazy module, DashboardModule. my other 2 modules, AppModule and LandingpageModule doesnt import anything from DashboardModule or its components...

Richard87 avatar Oct 06 '16 07:10 Richard87

Double check that global & local versions of angular-cli is the latest.

neilhem avatar Oct 06 '16 08:10 neilhem

Thanks, should work:

C:\Users\richa\Prosjekt\phono-frontend>ng --version
angular-cli: 1.0.0-beta.16
node: 6.3.0
os: win32 x64

C:\Users\richa\Prosjekt\phono-frontend>node_modules\.bin\ng --version
angular-cli: 1.0.0-beta.16
node: 6.3.0
os: win32 x64

C:\Users\richa\Prosjekt\phono-frontend>cd ..

C:\Users\richa\Prosjekt>ng --version
angular-cli: 1.0.0-beta.16
node: 6.3.0
os: win32 x64

Richard87 avatar Oct 06 '16 08:10 Richard87

Hmm, I think there are some strange "residual" files after I run ng serve --prod

I was trying to clean up the project, so I deleted all *.ngfactory.ts-files, aaand angular stopped finding my dashboard module again (didn't complain about route or anything, just couldn't find the module).

Then I added DashboardModule to AppModules imports, and ofcourse it works again.. BUT when I removed DashboardModule's import (both inside @NgModule and javascript import {} from ... it still works.

So my conclusion is that I am importing DashboardModule in some old files, and that's why it doesnt work, but when I clean out the build files, why doesn't angular find my DashboardModule?

I can't reproduce the error where angular can't find dashboard module, so I have literary no idea whats going on..

Richard87 avatar Oct 06 '16 09:10 Richard87

Same issue with 1.0.0-beta.16

import { NgModule }           from '@angular/core';
import { CommonModule }       from '@angular/common';
import { RouterModule } from '@angular/router';
import { DocumentsPage } from "./documents";

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([{ path: '', component: DocumentsPage}])
  ],
  declarations: [ DocumentsPage ],
})

export class DocumentsModule { }

and in my RouterModule.forRoot([...]): { path: 'documents', loadChildren: '/documents.module#DocumentsModule' }

When I replace loadChildren with component: fooCmp, DocumentsPage is not included in the main.bundle.js. Otherwise, using loadChildren includes the component in main.bundle.js

aaronleestic avatar Oct 06 '16 22:10 aaronleestic

figured out the culprit; import * as moment from 'moment' anywhere in the eagerly-loaded module will prevent lazy loading, and instead loadChildren modules will be included in the main bundle. I suspect importing d3 and other libraries will have the same issue.

The work around is to define the library in angular-cli.json' scripts definitions, and add a declare var moment: any in the typescript code, instead of an import.

However, workaround fails if other imported libraries has that import * as moment in its source code. For example, ng2-bootstrap's datepicker module : /

Workaround to that workaround is to fork valor's ng2-bootstrap datepicker...

aaronleestic avatar Oct 07 '16 05:10 aaronleestic

So in other words, if there is a import * from xxx anywhere we are f****?

What about the 100+ that exist in my node_modules folder? image

EDIT Is it solvable (by angular-cli or webpack), or must all modules specify their imports?

Richard87 avatar Oct 07 '16 06:10 Richard87

I did not yet investigate, but I made a repo that can reproduce this issue: https://github.com/aaronleeucla/angular-cli-lazy-load-bug-repro/blob/master/src/app/app-routing.module.ts

Running ng serve on this project, you can see that when either DatepickerModule is imported into NgModule or when moment() is used in the eagerly loaded MainPage component, lazy loading fails silently.

aaronleestic avatar Oct 07 '16 14:10 aaronleestic

Great work figuring out the cause @aaronleeucla! This definitely should not happen and is a bug.

filipesilva avatar Oct 10 '16 02:10 filipesilva

Can confirm, @aaronleeucla 's workaround makes angular-cli create multiple bundles again :+1:

alexciesielski avatar Oct 11 '16 07:10 alexciesielski

For nested routing setup (Gist here) like this:

export const eagerAppRoutes: Routes = [
  { path: '', children: [
      { path: 'home' },
      { path: '', 
        children: [

          { path: '',  /* loadChildren: './viewer/viewer.module#ViewerModule', */ 
            children: [

              { path: '_',
                children: [

                  { path: '', /* loadChildren: '../editor/editor.module#EditorModule', */
                    children: [

                      { path: '', component: EditorComponent },
                      { path: ':model', component: EditorComponent },],},]},]},]},
      { path: '**', redirectTo: 'home' },
    ]}];

only one chunk will be created (with ViewerModule), but EditorModule route will be ignored. There will be runtime errors cannot find module './editor/editor.module#EditorModule'.

If I add this to the app-routing.module.ts, (a route _ will never be matched here) both chunks will be created and routing will work:

{ path: '', canLoad: [AuthGuard], loadChildren: './viewer/viewer.module#ViewerModule' },
{ path: '_', canLoad: [AuthGuard], loadChildren: './editor/editor.module#EditorModule' }

Also note that loadChildren url in Viewer module should be ../editor/etc since this module is in sibling folder to the viewer module, but it does work with ./editor/etc (just one dot) if I include link in both places.

I'm using cli beta.17; angular 2.1.0; router 3.1.0

To recap: For nested lazy loaded routes (Gist here) only one chunk is created if I don't add both route definitions to the root; if I do, both chunks are generated and routing works as expected.

sasxa avatar Oct 16 '16 13:10 sasxa