Environment Based Dead Code Elimination in Angular

Netanel Basal
Netanel Basal
Published in
2 min readSep 30, 2020

--

There are times when we may want to run a piece of code only in either development or production mode. It can be something small, like logging some data to the console, or something much bigger, like loading an entire library.

In this article, I want to show you how we make sure that an undesired piece of code doesn’t reach our final bundle. Let’s start with the solution known to all:

We can use environment files — Angular CLI will load the relevant file based on the configuration, and remove the unreachable code when building to production. You can read more about the environment feature here.

This solution will work for most cases, but what about third-party libraries that can’t use the environment variable? How can they strip out code that should be used only in development mode from our main bundle?

If we take a look at the Angular CLI source code, we’ll see that it uses Terser to minify our code. One of the feature Terser provides is the conditional compilation API. It allows for the creation of global constants which can be configured at compile time. For example:

In the above example, Terser first replaces each occurrence of the DEBUG variable with false. Next, because we’ve enabled the dead_code option, Terser realizes that the line if (false) {…} is useless, and takes it out completely:

Live example

Now, if we take another look at the Angular CLI source code, we can see that it provides the ngDevMode variable as a global constant in Terser global_defs. What it means is that we can use it both in our application and in third-party libraries:

When we consume the component in our application and build it for production, Terser will strip out the code inside the if statement from our bundle.

Note that if you want to support a server-side compilation, you’ll need to add one more check:

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • error-tailer — Seamless form errors for Angular applications
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests
  • Error Tailor — Seamless form errors for Angular applications

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.