In recent Angular versions (>=17), if we want to use a Pipe or directives like NgClass
we can follow two approaches:
- Importing the
CommonModule
. Eg:
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-messages',
imports: [CommonModule],
templateUrl: './messages.component.html',
styleUrl: './messages.component.scss'
})
[...]
- Importing the specific directive/pipe. Eg:
import { NgClass, DatePipe } from '@angular/common';
@Component({
selector: 'app-messages',
imports: [NgClass, DatePipe],
templateUrl: './messages.component.html',
styleUrl: './messages.component.scss'
})
[...]
I know that importing CommonModule
is more handy because with just one import we get a bunch of directives but if I want to use just one or two directives from that module, what is best option in performance terms? Or is it something that doesn’t matter because at the end this module becomes imported from other places or modules?
Thanks!
There is no perf difference, it just helps you to have a better view of your dependencies and potentially remove unused ones.
Also in v19, Angular will tell you if there is an unused standalone import but it won’t tell you the Module import is useless.
There is something we call it Angular’s tree-shaking process
CommonModule provides a collection of commonly used directives (NgIf, NgForOf, NgClass, …) and pipes (DatePipe, CurrencyPipe, …) and importing CommonModule means that you get all of these features in your module and this import is usually done at the module level.
but at the end of the day Angular’s tree-shaking process during building for production will generally eliminate unused code, so unused pipes or directives won’t be included in the final bundle.
about the runtime we have lots of overloaded features and data which importing all CommonModule is nothing compare to them 🙂