Conditional module imports in Angular

 

Whenever you’re introducing third-party services to your Angular application there are cases that you need those services only for development, testing or production. To keep your builds as fast and small as possible you want to import those services conditionally.

The best examples are:

  • You’re using ngrx/store and the ngrx/store-devtools module. You want to use ngrx/store-devtools only in development and prevent it from being imported in production.
  • You’re using a production logging service like logrocket and want to initiate this service only while in production, not while doing development.

Since initiating logging services is quite specific to the service you’re using i will not go into that. You can however follow the same pattern that importing ngrx/store-devtools only in development, will use. Importing ngrx/store-devtools only in development can be done like this:

// angular
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { StoreModule } from '@ngrx/store';
import { RouterModule } from '@angular/router';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

// modules
import { Home } from './home';

// components
import { Base } from '../components/base';

// router
import { routes } from '../router/root';

// import dev only modules
let dev = [
StoreDevtoolsModule.instrument({
maxAge: 10,
}),
];

// if production clear dev imports and set to prod mode
if (process.env.NODE_ENV === 'production') {
dev = [];
enableProdMode();
}

/**
 * Root module.
 * Iniate global providers, and import all modules
 *
 * @export
 * @class Root
 */
@NgModule({
bootstrap: [
Base,
],
declarations: [
Base,
],
imports: [
Home,
RouterModule.forRoot(routes, { useHash: true }),
StoreModule.forRoot(reducers.reducerToken),
...dev,
],
providers: [
],
})
export class Root { }

// startup application
platformBrowserDynamic().bootstrapModule(Root);

The trick

We define an array named dev and import/configure our storeDevtoolsModule in that array. We then check if we’re in production using the NODE_ENV variable. If we are in production, we clear the dev array again. This dev array is imported into the module declaration using the spread operator. When using the spread operator in an array it allows you to easily place an expanded version of an array into another array. This is demonstrated in the example below:

let list = [1, 2];
list = [...list, 3, 4];
console.log(list); // [1,2,3,4]

I hope this little trick helps you to do conditional module imports.

Source: https://hackernoon.com/conditional-module-imports-in-angular-518294aa4cc

Share :

Leave a Reply

Your email address will not be published. Required fields are marked *