Picture of Angular and Webpack logos hugging each-other and the words `Magic comments` on top of Webpack logo. Credit https://angular.io/ https://webpack.js.org/

Webpack magic comments

Georgi Parlakov

--

Lazy loading hard dependencies in Angular apps

Using Webpack dynamic imports we can instruct Webpack to split out the module and lazy load it only when user attempts this one very rare thing.

I recently did some optimization work on the web app we maintain — https:/propy.com. The link points to the Angular part of the app. Its a medium sized Angular application with lots of third party dependencies.

One of the challenges we faced was that a lot of JavaScript was downloaded which was used by a small percentage of the people. For example if 100 people visit maybe will 10 buy a real estate.
One thing we did was lazy loading parts of the app. But in the app some lazy loaded modules still loaded external dependencies that we used extremely rarely. Once per customer.
And that’s not once per visit! Rather — during all visits ever we’ll only use this JavaScript once for this one customer. This was in the component rendering the personal user space — my settings, password etc.

From the Angular Ahead Of Time (currently Angular 5) compiler our PersonalModule depended hard on the bip39, ether and one more library totaling about 1.5 MB of JavaScript and JSON. This is a lot of data and CPU for something that’s required almost never. It’s hard to instruct the compiler with some degree of granularity with Angular CLI largely owning the compile config. There was no way using .angular-cli.json to tell Angular — these three libraries are to be in their own lazy loaded module(as in JavaScript module).

Based on James Gillmore article and webpack docs we ended up with this solution:

Using Webpack dynamic imports (I prefer magic comments :) we can instruct Webpack to split out the module and lazy load it only when user attempts this one very rare thing.

--

--

Georgi Parlakov
Georgi Parlakov

Written by Georgi Parlakov

Angular and DotNet dev. RxJs explorer. Testing proponent. A dad. Educative.io course author. https://gparlakov.github.io/

No responses yet