问题
Lazy loading is a commonly used technique. However, in Angular it seems that the granularity level of this technique stops at the module level.
That means that you can have module main that loads in the browser, and then on special occasion module B and C and D can be loaded lazily.
Almost all tutorials on web explain that. However, is there a way to load components lazily?
Consider this simple example that user goes inside the application, and when clicks "invoices" link, URL changes to the new route /invoice/list
and a progress bar shows loading, while the invoices
component including HTML and JS is being loaded inside the browser, is registered dynamically with the main module, and is being shown in the relevant outlet. Is that possible with Angular?
回答1:
Lazy loading a component is not possible. Reason for this behavior is the structure of angular. Components in angular have to be part of a module. Angular module is a container where you define all the components, services, pipes e.t.c. present inside. While building the application dist, all the dependencies declared in the module are included to make a chunk (transpiled js code). All the directly imported modules together form the main chunk whereas modules marked as lazily loaded form a separate chunk that sits on the server untill the respective route is hit and a call for it is made from the client. Now components do not form a chunk and hence it is not possible
回答2:
Currently (Angular 8 timeframe) there are two 3rd party libraries that make lazy-loading of components easier:
- ngx-loadable: https://github.com/mohammedzamakhan/ngx-loadable
- hero-loader: https://www.npmjs.com/package/@herodevs/hero-loader
Note: both of these libraries are built upon NgModuleFactoryLoader, which is deprecated in Angular 8, but there is no alternative yet ...
- Class marked as deprecated: https://angular.io/api/core/NgModuleFactoryLoader
- Explanation of Rob Wormald of the Angular Team: https://twitter.com/robwormald/status/1143981312237137925
The Angular team has announced that lazy loading of components should become easier with Ivy (Angular 9?), but it is not clear yet how this will look like...
回答3:
A bit hacky ... but possible (future versions of Angular (beyond ver. 7) will implement an easier apporach)
https://blog.angularindepth.com/dynamically-loading-components-with-angular-cli-92a3c69bcd28
来源:https://stackoverflow.com/questions/48124682/is-there-a-way-to-lazy-load-components-not-modules-in-angular