https://github.com/gdfreitasdev/angular-modules-lazy-loading-sample
Angular sample for lazy loading routed components
https://github.com/gdfreitasdev/angular-modules-lazy-loading-sample
angular lazy-loading
Last synced: about 1 month ago
JSON representation
Angular sample for lazy loading routed components
- Host: GitHub
- URL: https://github.com/gdfreitasdev/angular-modules-lazy-loading-sample
- Owner: gdfreitasdev
- Created: 2021-06-21T21:25:15.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2021-09-08T01:12:07.000Z (almost 5 years ago)
- Last Synced: 2025-08-30T06:49:34.420Z (10 months ago)
- Topics: angular, lazy-loading
- Language: TypeScript
- Homepage:
- Size: 141 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# angular-modules-lazy-loading-sample
Setup lazy loading for routed components
## Step by step
### Create new feature modules
Create Customer module using CLI
```
ng generate module customers --route customers --module app.module
```
Create Orders module using CLI
```
ng generate module orders --route orders --module app.module
```
The commands above will auto register routes like below, with `loadChildren` implementation using native ESM dynamic imports syntax.
```ts
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
```
### Add router links
```html
{{title}}
Customers
Orders
Home
```
### Checkout lazy load in action
```
ng serve
```
or
```
yarn start
```
Checkout it's behaviour by navigating on http://localhost:4200
Notice JavaScript chunks being fetched while routing by looking into network inspection of browser's devtools. It also contains components styles that will be injected in the DOM.
### Bonus: Pre-loading strategy
You can also configure to automatically pre load modules to improve user experience by setting the strategy on routing module. This prevent users to have to wait for files to be downloaded when routed.
```ts
import { PreloadAllModules } from '@angular/router';
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
});
```
## References
- [Lazy-loading feature modules](https://angular.io/guide/lazy-loading-ngmodules)