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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With