Aniruddha Das
Aniruddha Das

Reputation: 21688

how to generate a lazy loading module using angular cli

I have an existing angular cli application and I want to add a new module to my application which will be loaded lazily

I know angular cli provides command to generate modules which can be lazily loaded, what is the quick command I need to type to do below thing

When I try ng generate module module-name --route=app --routing=true, it gives me below error

Module option required when creating a lazy loaded routing module.

Upvotes: 8

Views: 19333

Answers (2)

Aniruddha Das
Aniruddha Das

Reputation: 21688

Command:

ng generate module new-module-name --module parent-module --routing true --route path-string
  • ng generate module module-name: It will generate a module with name new-module-name.
  • --module parent-module: The newly created module will be added into the parent module which is app module in most of the time.
  • --routing true: Generate routing and a default component to be lazily loaded
  • --route path-string: path-string will be added as a router in the parent-module routing config.

you will see the angular-cli output as

CREATE src/app/modules/module-name/module-name-routing.module.ts (373 bytes) CREATE src/app/modules/module-name/module-name.module.ts (400 bytes) CREATE src/app/modules/module-name/module-name.component.scss (0 bytes) CREATE src/app/modules/module-name/module-name.component.html (29 bytes) CREATE src/app/modules/module-name/module-name.component.spec.ts (678 bytes) CREATE src/app/modules/module-name/module-name.component.ts (301 bytes) UPDATE src/app/app-routing.module.ts (1398 bytes) Done

Upvotes: 20

Sagar Agrawal
Sagar Agrawal

Reputation: 657

You can generate a lazy loaded module using below command:

ng generate module customers --route customers --module app.module

Excerpt from the angular documentation: This creates a customers folder having the new lazy-loadable feature module CustomersModule defined in the customers.module.ts file and the routing module CustomersRoutingModule defined in the customers-routing.module.ts file. The command automatically declares the CustomersComponent and imports CustomersRoutingModule inside the new feature module.

Because the new module is meant to be lazy-loaded, the command does NOT add a reference to the new feature module in the application's root module file, app.module.ts. Instead, it adds the declared route, customers to the routes array declared in the module provided as the --module option.

For details refer to the official angular docs here: https://angular.io/guide/lazy-loading-ngmodules

Upvotes: 13

Related Questions