Lazy loading an ES Module helps to split your app files into smaller chunks (multiple smaller .js files).

Benefits of code splitting

  • Keeps your main.js as small as possible (which is important for SEO an UX).
  • Conditionally loading a module (e.g. Angular Universal for Server-Side Rendering / SSR).
async ngOnInit(): Promise<void> {
  if (isPlatformBrowser(this.platformId)) {
    this.L = await import('leaflet');
  }
}

As you can see it is very easy to do with JavaScript (ES2015). This will put 'leaflet' into it's own chunk .js file.

How to keep type safety without eager loading the module

TypeScript allows us to only import type definitions. (see doc)

import type * as L from 'leaflet';

Then, we can use these types without actually loading the module.

export class LeafletService {
  L!: typeof L;
}