Netanel Basal

Learn development with great articles

Follow publication

Using TypeScript Dynamic Imports in Angular

TypeScript 2.4 added support for dynamic import() expressions, which allow us to asynchronously load and execute ECMAScript modules on demand.

This means that we can conditionally and lazily import other modules and libraries.

In this article, we will see how we can leverage this feature in Angular, so we can produce a smaller bundle. Let’s take a real example from our application. ( Datorama BTW )

We have a page full of widgets, and we provide our customers the ability to export them to Excel.

Under the hood, we are using a library called xlsx. It would be a waste to add the library to our initial bundle because each client will have to download and parse it even though he probably will not use it.

A better decision would be to lazy load the library when the user clicks on the export button.

Let’s see how we can do this.

With Promises

Assuming you’re working with the angular-cli, that’s all you have to do, otherwise, you will need to add the support yourself. ( webpack code splitting, etc. )

The cool thing is that we can use it with RxJS and add it to every stream. For example:

With RXJS
angular-cli

The last thing that we need to do is simply setting the module value in your tsconfig.app.json file to esnext.

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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Netanel Basal
Netanel Basal
Netanel Basal
Netanel Basal

Written by Netanel Basal

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

Responses (6)

Write a response