Use the ES6 spread operator ...
to clean up and maintain your @NgModule declaration with ease.
Jump down to the files if you want to skip the explanation.
-
Under your Ionic project's
src/
directory, add the following directories as needed.pages/
for Ionic's Page @Components, generated with$ ionic g page <PageName>
providers/
for Angular's @Injectable services, generated with$ ionic g provider <ServiceName>
components/
for custom @Components which are not Ionic pagesdirectives/
for custom @Directivesimports/
for non-core Angular modules and third-party modulespipes/
for custom @Pipes
-
Make an
index.ts
file at the root of each directory. -
For each directory, import every module into the
index.ts
file. Add the modules to an exported array.src/components/index.ts (example)
import { MyComponent } from './my-component/my-component'; import { OtherComponent } from './other-component/other-component'; export const Components = [ MyComponent, OtherComponent ];
-
Create a file to act as an alias to each directory's
index.ts
file. This allows us to import all of the module arrays from the same place. I called mineapp.modules.ts
and put it in thesrc/app/
directory.src/app/app.modules.ts
export * from '../components'; export * from '../directives'; export * from '../imports'; export * from '../pages'; export * from '../pipes'; export * from '../providers';
-
Import the module arrays above the
@NgModule
declaration insrc/app/app.module.ts
.src/app/app.module.ts
import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { Components, Directives, AngularModules, ThirdPartyModules, Pages, Pipes, Services } from './app.modules';
-
Use the ES6 spread operator to add the contents of the module arrays to
@NgModule
.... @NgModule({ declarations: [ MyApp, ...Pages, ...Components, ...Directives, ...Pipes ], imports: [ IonicModule.forRoot(MyApp), ...AngularModules, ...ThirdPartyModules ], bootstrap: [ IonicApp ], entryComponents: [ MyApp, ...Pages ], providers: [ { provide: ErrorHandler, useClass: IonicErrorHandler }, ...Services ] }) export class AppModule {}