Check out myAngular article series with live demos and Facebook group Angular - Advanced Topics

Removing Whitespace in Angular Templates

Torgeir "Tor" Helgevold
- JavaScript Developer and Blogger
Published: Mon Sep 04 2017

This post is a write-up of an experiment where I measure the impact of removing whitespace from Ahead of Time Compiled (AoT) templates.

I won’t get into the details of AoT in this post.

If you are new to AoT, I invite you to check out my Google Meetup talk about AoT and Prod builds here.

In short, AoT converts Angular html templates to regular JavaScript.

Whitespace

During AoT, what happens to whitespace elements in the original templates?

In versions 2 and 4 of Angular the whitespace is preserved, and included in the JavaScript representation of the template.

This is not desirable since whitespace between elements is typically not significant when rendered by the browser.

Unfortunately you can’t remove it by simply running Uglify on the generated JavaScript. That won’t work since AoT converts the original html to a series of JavaScript strings. Uglify won’t remove whitespace in strings since it will change the meaning of the string.

To be fair, Uglify doesn’t know that these strings actually represent html elements where whitespace is generally not significant.

The good news is that Angular 5 will offer a way to remove whitespace during AoT.

There will be a new compiler flag called “preserveWhitespaces”. The flag can be used to tell the compiler to not incorporate the original whitespace in the generated AoT JavaScript. You control this behavior through compilerOptions in tsconfig.json.

Results

So how much of a difference does whitespace removal make?

The results will vary based on the size of the templates in your application. I tested it with a “medium” size application, and noticed a difference of only 1k (gzipped).

Larger apps will likely benefit more though.

However, there is a limit to how much you can gain from removing whitespace. Most people just don’t include large amounts of whitespace in their templates.

That said I encourage you to try it in your own application. It’s basically “free” optimization since all you have to do is flip a flag to remove template whitespace.

If you liked this article, share it with your friends on social media:

We also have a new Facebook group about advanced Angular topics.

I invite you to follow me on twitter