Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lazy load HammerJS in Angular 9 project?

I use HammerJS in my Angular project for a few gestures like panleft and panrigth in lazy load component. When I build app, lazy load component is in separate bundle, but hammer.js stay in node_modules in main bundle. And it works as expected. But how to load hammer.js in separate lazy module to reduce main bundle size?

I use Angular 9 with Angular Material. HammerJS is not required for material since ng9.

To install HammerJS (and it works with ng9) I:
1. run npm install --save hammerjs
2. add to main.ts - import 'hammerjs'
3. import HammerModule to app.module.ts (required for ng9)
also I have custom config in app.module.ts:

@Injectable()
export class HammerCustomConfig extends HammerGestureConfig {
  overrides = { 'pinch': { enable: false }, 'rotate': { enable: false } } as any;
}

that provided like { provide: HAMMER_GESTURE_CONFIG, useClass: HammerCustomConfig }

I tried and it DOESN'T work:
1. move import 'hammerjs' to lazy load module (but hammer.js repalced to bundle of lazy load module)
2. move HammerModule to lazy load module
2. move HammerModule with custom config to lazy load module
4. 1 + 2
5. 1 + 3

like image 382
Andriy Zozulya Avatar asked Sep 14 '25 19:09

Andriy Zozulya


2 Answers

Here is an example of how the module (in my case "Carousle Module") looks like.

Leave the HammerModule in your main module ( app.module.ts ) imports.

import { HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser';
import { CustomHammerConfig } from './hammer-config';


import 'hammerjs'; // <-- import it here (not in your main.ts)

@NgModule({
  imports: [
    CommonModule,
    HammerModule, // <-- put it only here (not in your AppModule)
  ],
  exports: [CarouselComponent],
  providers: [
    // config may be provided in module where needed or in app.module
    {
      provide: HAMMER_GESTURE_CONFIG,
      useClass: CustomHammerConfig,
    },
  ],
  declarations: [CarouselComponent],
})
export class CarouselModule {}


In bundle analysis, you may see the hammer is part of feature chunk (module) and not the main module.

build analysis

like image 164
Vojtech Avatar answered Sep 17 '25 09:09

Vojtech


Moving import 'hammerjs' from main.ts to lazy load COMPONENT resolve this problem.
Import of HammerModule and custom config should stay in app.module.ts.

like image 36
Andriy Zozulya Avatar answered Sep 17 '25 11:09

Andriy Zozulya