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

Lazy loading module from library package located in node_modules fails to build.

Open thekhoi opened this issue 9 years ago • 80 comments

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Versions.

@angular/cli: 1.0.4
node: 6.10.2
os: win32 x64
@angular/cli: 1.0.4
@angular/common: 4.1.3
@angular/compiler: 4.1.3
@angular/core: 4.1.3
@angular/forms: 4.1.3
@angular/http: 4.1.3
@angular/platform-browser: 4.1.3
@angular/platform-browser-dynamic: 4.1.3
@angular/router: 4.1.3
@angular/compiler-cli: 4.1.3

Repro steps.

I've modified the quick start library from @filipesilva and copied the output folder to my node_modules/quickstart-lib directory.

https://github.com/filipesilva/angular-quickstart-lib

Modification includes a routing module to add a child route.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LibComponent } from './component/lib.component';
const childRoutes: Routes = [
  {
    path: '',
    component: LibComponent
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(childRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class LibRoutingModule { }

which is then imported into the main LibModule file.

import { NgModule } from '@angular/core';
import { LibRoutingModule } from './lib-routing.module';
import { LibComponent } from './component/lib.component';
import { LibService } from './service/lib.service';

@NgModule({
  declarations: [LibComponent],
  imports: [LibRoutingModule],
  providers: [LibService],
  exports: [LibComponent]
})
export class LibModule { }

In my host application, I created a simple route to lazy load the module from the library

const routes: Routes = [
  {
    path: 'quickstart',
    loadChildren: 'quickstart-lib#LibModule'
  },
  {
    path: 'preferences',
    loadChildren: 'app/preferences#PreferencesModule'
  },
  ...HomeRoutes
];


The log given by the failure.

PS C:\Workspace\scratch\Ng4Starter\host> ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
 11% building modules 14/23 modules 9 active ...gular\platform-browser-dynamic.es5.js(node:19124) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic,
 see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
 11% building modules 15/23 modules 8 active ...gular\platform-browser-dynamic.es5.js(node:19124) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic,
 see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
Hash: c46342c7aafb5ce0f53e
Time: 14214ms
chunk    {0} 0.chunk.js, 0.chunk.js.map 20.5 kB {3} [rendered]
chunk    {1} 1.chunk.js, 1.chunk.js.map 793 bytes {0} {3} [rendered]
chunk    {2} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 157 kB {7} [initial] [rendered]
chunk    {3} main.bundle.js, main.bundle.js.map (main) 72.5 kB {6} [initial] [rendered]
chunk    {4} styles.bundle.js, styles.bundle.js.map (styles) 229 kB {7} [initial] [rendered]
chunk    {5} scripts.bundle.js, scripts.bundle.js.map (scripts) 162 kB {7} [initial] [rendered]
chunk    {6} vendor.bundle.js, vendor.bundle.js.map (vendor) 3.36 MB [initial] [rendered]
chunk    {7} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]

ERROR in ./~/quickstart-lib/quickstart-lib.d.ts
Module build failed: Error: Debug Failure. False expression: Output generation failed:=>C:/Workspace/scratch/Ng4Starter/host/node_modules/quickstart-lib/quickstart-lib.d.ts
    at Object.assert (C:\Workspace\scratch\Ng4Starter\host\node_modules\typescript\lib\typescript.js:3259:23)
    at Object.transpileModule (C:\Workspace\scratch\Ng4Starter\host\node_modules\typescript\lib\typescript.js:76181:18)
    at TypeScriptFileRefactor.transpile (C:\Workspace\scratch\Ng4Starter\host\node_modules\@ngtools\webpack\src\refactor.js:161:27)
    at Promise.resolve.then.then.then.then (C:\Workspace\scratch\Ng4Starter\host\node_modules\@ngtools\webpack\src\loader.js:361:37)
    at process._tickCallback (internal/process/next_tick.js:109:7)
 @ ./src async
 @ ./~/@angular/core/@angular/core.es5.js
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
webpack: Failed to compile.

Desired functionality.

I would like to distribute my code as an NPM library and have the CLI support lazy loading the module that is located in the 'node_modules' directory.

Modules located in the same application directory are lazy loaded just fine.

Mention any other details that might be useful.

https://github.com/filipesilva/angular-quickstart-lib

thekhoi avatar May 18 '17 18:05 thekhoi

A proxy module works for now, but looking forward to a solution in 7.0.

un33k avatar Sep 10 '18 21:09 un33k

@tiagoa Are you sure that this is real lazy loaded? Since you use return MyLibModule, and in that way it needs to be imported. At the end, it is working, but it is not lazy loaded.

mnicic avatar Sep 26 '18 13:09 mnicic

@mnicic yeah, @tiagoa solution is not lazy loading. If there's an import in your routing you will bring all the source together. Currently the only working solution is the proxy, and seeing the lack of interest from the development team on this issue, until someone develops another routing solution for angular, there won't be alternative.

aitorllj93 avatar Sep 26 '18 15:09 aitorllj93

@mnicic yeah, @tiagoa solution is not lazy loading. If there's an import in your routing you will bring all the source together. Currently the only working solution is the proxy, and seeing the lack of interest from the development team on this issue, until someone develops another routing solution for angular, there won't be alternative.

What's the problem with the working solution? The proxy module is lazy loaded by the router. Your only overhead is the proxy module around your actual module, that you wanted to lazy load.

totkeks avatar Sep 26 '18 17:09 totkeks

@mnicic yeah, @tiagoa solution is not lazy loading. If there's an import in your routing you will bring all the source together. Currently the only working solution is the proxy, and seeing the lack of interest from the development team on this issue, until someone develops another routing solution for angular, there won't be alternative.

What's the problem with the working solution? The proxy module is lazy loaded by the router. Your only overhead is the proxy module around your actual module, that you wanted to lazy load.

The problem with the working solution is that it's a hack to make it work around an issue, that it's not being able to lazy load modules installed through npm. This produces inconsistent source code on applications, where you have local modules without the need of a proxy module, and node modules with a proxy requirement. But things get worse, this issue, is not mentioned on official angular documentation, so if you try to do this at first time, you lose time trying to make work something that should work until you google it and find this issue growing with comments from people who find this issue in their projects over and over again. Try to keep the "modular" philosophy angular proposes and then publish your reusable routed modules into npm or your private node repository, and now you have to create a proxy for every "reusable" module that isn't reusable without it after all.

aitorllj93 avatar Sep 26 '18 18:09 aitorllj93

I was able to make it work use this function to load the module

lazyModuleLoad = function <T>(cl: Type<T>): any { return function (): Type<any> | NgModuleFactory<any> | Promise<Type<any>> | Observable<Type<any>> { return new Promise<Type<any>>(resolve => resolve(cl)); }; }; And in path I call the function like that:

path: '', loadChildren: lazyModuleLoad(SomeModule)

gravatasufoca avatar Oct 27 '18 02:10 gravatasufoca

I was able to make it work use this function to load the module

lazyModuleLoad = function <T>(cl: Type<T>): any { return function (): Type<any> | NgModuleFactory<any> | Promise<Type<any>> | Observable<Type<any>> { return new Promise<Type<any>>(resolve => resolve(cl)); }; }; And in path I call the function like that:

path: '', loadChildren: lazyModuleLoad(SomeModule)

Your solution will compile the module at runtime and won´t load it lazy. And it won´t work with AOT compile.

nekator avatar Oct 29 '18 07:10 nekator

Hi, I'm developing a dashboard like application. I am developing widgets in angular cli libraries, then compiling these libraries and publishing them to our private NPM registry. These libraries export a NgModule which declares its widgets and makes them entryComponents for dynamic rendering. Then, in the host app, which installs these NPM packages, I am trying to dynamically load these modules, if requested via configuration, to get their widgets' component factories. The problem I'm facing is that I can't seem to be able to lazy load these precompiled NgModules in any way. I've tried following many good guides I found in stackoverflow but those always talk about loading source files that export an NgModule, not something that is already built in AOT mode from an NPM package. Reading this topic it seems it is not doable... and that I should publish NPM packages containing the source code instead of a compiled library. Is it the case or is there a workaround/official fix after 1 and a half years this topic was open?

Etchelon avatar Dec 03 '18 11:12 Etchelon

Hi, I'm developing a dashboard like application. I am developing widgets in angular cli libraries, then compiling these libraries and publishing them to our private NPM registry. These libraries export a NgModule which declares its widgets and makes them entryComponents for dynamic rendering. Then, in the host app, which installs these NPM packages, I am trying to dynamically load these modules, if requested via configuration, to get their widgets' component factories. The problem I'm facing is that I can't seem to be able to lazy load these precompiled NgModules in any way. I've tried following many good guides I found in stackoverflow but those always talk about loading source files that export an NgModule, not something that is already built in AOT mode from an NPM package. Reading this topic it seems it is not doable... and that I should publish NPM packages containing the source code instead of a compiled library. Is it the case or is there a workaround/official fix after 1 and a half years this topic was open?

I already posted this in a similar issue (could be a duplicate, but not entirely sure). https://github.com/angular/angular-cli/issues/12859#issuecomment-437582885

The loading from webpack is actually working fine, as in it found the correct modules to load via lazy loaded references, but the actual ngfactories for those modules have not been build in the process.

You can try my workaround. Basically what you want is to somehow force the compiler to build your factory, but don't have it bundled into the main chunk but into their respective separate chunks.

totkeks avatar Dec 03 '18 11:12 totkeks

Hi, I'm developing a dashboard like application. I am developing widgets in angular cli libraries, then compiling these libraries and publishing them to our private NPM registry. These libraries export a NgModule which declares its widgets and makes them entryComponents for dynamic rendering. Then, in the host app, which installs these NPM packages, I am trying to dynamically load these modules, if requested via configuration, to get their widgets' component factories. The problem I'm facing is that I can't seem to be able to lazy load these precompiled NgModules in any way. I've tried following many good guides I found in stackoverflow but those always talk about loading source files that export an NgModule, not something that is already built in AOT mode from an NPM package. Reading this topic it seems it is not doable... and that I should publish NPM packages containing the source code instead of a compiled library. Is it the case or is there a workaround/official fix after 1 and a half years this topic was open?

I already posted this in a similar issue (could be a duplicate, but not entirely sure). #12859 (comment)

The loading from webpack is actually working fine, as in it found the correct modules to load via lazy loaded references, but the actual ngfactories for those modules have not been build in the process.

You can try my workaround. Basically what you want is to somehow force the compiler to build your factory, but don't have it bundled into the main chunk but into their respective separate chunks.

I don't think the issue is the same. I am trying to load modules from NPM packages without really knowing if these modules are even installed in the host app. This app, at startup, gets a configuration object from the server which tells which plugins should be enabled. The app then tries to load these plugins via http request (the paths to the NgModules contained in the NPM packages come with the configuration and aren't written anywhere in the code, so webpack can't know them) and use the ngfactory to then extract its components. All the examples I've seen just load the lib.module.ts#LibModule and then feed that file to the angular compiler. I want to download via HTTP the already compiled ngfactory (compiled by the external developer that publishes the NPM package with its widgets) and extract its components.

Etchelon avatar Dec 03 '18 11:12 Etchelon

@angular-devkit/architect          0.10.7
@angular-devkit/build-angular      0.10.7
@angular-devkit/build-ng-packagr   0.10.7
@angular-devkit/build-optimizer    0.10.7
@angular-devkit/build-webpack      0.10.7
@angular-devkit/core               7.0.7
@angular-devkit/schematics         7.0.7
@angular/cli                       7.0.7
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.0.7
@schematics/angular                7.0.7
@schematics/update                 0.10.7
ng-packagr                         4.4.5
rxjs                               6.3.3
typescript                         3.1.6
webpack                            4.19.1

Both workarounds worked for me: https://github.com/angular/angular-cli/issues/6373#issuecomment-386625097 << preferred https://github.com/angular/angular-cli/issues/6373#issuecomment-319116889

sqonde avatar Dec 12 '18 11:12 sqonde

So why is this not a priority? Lets say we have a bigger business application where all pages are located in a lib. For each customer we create a custom app out of the pages. When you have so many pages Lazy Loading is the way to go because the startup time would be too high otherwise. Now I have to create a wrapper module for 50 pages to make it work correctly?? That is not a reasonable solution at all...

digaus avatar Dec 14 '18 08:12 digaus

I'm guessing because the Ivy renderer will fix this issue (and change the way to deal with these things anyway) and they don't want to spend time fixing the "old" behavior.

woppa684 avatar Dec 14 '18 09:12 woppa684

I'm guessing because the Ivy renderer will fix this issue (and change the way to deal with these things anyway) and they don't want to spend time fixing the "old" behavior.

Well, that is a valid and reasonable explanation, however, this issue and other related issues are hunting angular community since quite a while now, while having no official statement(apart from Ivy recently).

Sure, Ivy will fix that, but why didn't fix happened earlier(without Ivy) given the fact the issue really puts a stain on Angular itself IMHO.

klemenoslaj avatar Dec 14 '18 11:12 klemenoslaj

@adamlubek , you're right. It looks like there was an issue with the node package I created for testing. My package name was scoped @foo/bar but the "importAs" attribute in my bar.metadata.json file was set to "bar".

I know this is a while ago, but how did you manage to solve this? If I change the importAs attributes manually in the generated metadata file for my built libraries indeed it works, but how can I instruct Angular CLI to use the correct (scoped) importAs statement?

woppa684 avatar Dec 18 '18 07:12 woppa684

With the recent version of Angular CLI (7.1.4), I might have found another workaround, which is much cleaner. You can find it in angular-demo-lazy-route-libraries repository.

Before I had a workaround with wrapper module, that statically imported lazy module and exported it. Then I used that wrapper module to configure loadChildren property in my routes.

But I accidentally discovered that (at least with 7.1.4) I do not need a wrapper module, instead, I can just statically import it in some file, but I do not need to import this file anywhere.
This file in the shared repo is called __fake-imports.ts in the application. Note the comment, it should never be imported.

By doing this I can keep imports in my routes simple:

{
  path: 'lazy',
  loadChildren: 'lazy-component#LazyComponentModule',
}

Can anyone test the repo as well (more info in README.md)? I tested it on OS X Mojave and Manjaro Linux with latest npm, node and Angular CLI.


If that indeed works and I didn't miss something, that means Angular CLI is already close to supporting this feature. The question is if they will go the extra mile.

klemenoslaj avatar Jan 04 '19 17:01 klemenoslaj

@klemenoslaj Nice catch! Much cleaner then wrapping lib modules into app modules. For jit compilation, you can make that work with setting up the path in your tsconfig. I'm used to to this during development to build both app and lib source with webpack, see https://github.com/angular/angular-cli/issues/10369. While this is generally not recommended, it's quite convenient during development. I have a pipeline running production builds on every commit (using a separate tsconfig), so the risk for libs no being build correctly is mitigated.

I was able to test the repo and further enhance it with several (ng-packagr) sub modules. It's even working with the route config in the lib code.

tobi-or-not-tobi avatar Jan 08 '19 14:01 tobi-or-not-tobi

@tobi-or-not-tobi, great ;) And feel free to make a pull request to my repo adding JIT and other enhancement, so that people could benefit 👍

klemenoslaj avatar Jan 09 '19 10:01 klemenoslaj

Hi all,

This thread was opened a while ago. Having so comments makes it hard for people to find information in anything but the latest comments. But on the other hand I don't think most people would go through all of the comments anyway. New users that see this thread mostly read the first and latest comments and lose things said in between.

So for the reasons stated above (high volume of comments, hidden comments, hard to report and inform people) I'm locking this issue to prevent this comment from being lost as new comments come in.

Thank you to everyone that reported and helped diagnose the problems and provided workarounds.

Our recommended approach to lazy load a library within an angular workspace or node modules, is to use a proxy/wrapper module. With this approach lazy loading will works in both JIT and AOT mode. There are other solutions that work solely in AOT mode such as tsconfig imports however for a better development experience we don't encourage this.

Below find an example of the recommended approach;

lazy/lazy.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { LibModule, LazyComponent } from 'my-lib';

@NgModule({
  imports: [
    LibModule,
    RouterModule.forChild([
      { path: '', component: LazyComponent, pathMatch: 'full' }
    ])
  ]
})
export class LazyModule { }

app.module.ts

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
  ],
  imports: [
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full'},
      { path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule'},
    ]),
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

alan-agius4 avatar Jan 10 '19 08:01 alan-agius4

Hi all,

I am going to close this as following a convo with @alxhub. Lazy loading should happen at an application and not a library level. Hence the above approach is the recommended and the supported way to lazy load a library module in your application.

Related to: https://github.com/angular/angular/issues/31893#issuecomment-516615243

alan-agius4 avatar Sep 19 '19 16:09 alan-agius4