paint-brush
Conditional module imports in Angularby@luukgruijs
15,998 reads
15,998 reads

Conditional module imports in Angular

by Luuk GruijsSeptember 17th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Whenever you’re introducing third-party services to your <a href="https://hackernoon.com/tagged/angular" target="_blank">Angular</a> 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.

Company Mentioned

Mention Thumbnail
featured image - Conditional module imports in Angular
Luuk Gruijs HackerNoon profile picture

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.

Photo by WEB AGENCY on Unsplash

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:

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:

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

Thanks for reading. Please hit the clap button if you liked this article. Any feedback? Let me know. Also check my other articles:

Follow me on Medium or twitter and let’s connect on LinkedIn