Angular中CommonModule与BrowserModule的区别及选型建议
Hey there! As an Angular newbie, it makes total sense to wonder about the difference between CommonModule and BrowserModule—let’s break this down in plain terms so you know exactly when to use which.
Core Differences
BrowserModule
- It’s Angular’s root-module-only module built specifically for browser environments.
- It includes everything
CommonModulehas (all those handy directives like*ngIf,*ngFor, and pipes likeDatePipe,UpperCasePipe). - On top of that, it adds browser-specific initialization logic and services—things like DOM rendering setup, the
Titleservice for managing page titles, and base providers for browser-specific features. - Critical rule: Only import this once in your root
AppModule. If you try to import it in a feature module, you’ll get an error—some of its services are singletons, and duplicate imports cause conflicts.
CommonModule
- It’s Angular’s utility module for all non-root modules (feature modules, lazy-loaded modules, etc.).
- It provides the most commonly used Angular directives and pipes—think
*ngIf,*ngFor,*ngSwitch,AsyncPipe,CurrencyPipe, and more. - No browser-specific initialization code here, so it’s safe to import in as many feature modules as you need without singleton conflicts.
When to Use Which
For Your Root Module (AppModule)
Always import BrowserModule here. It bootstraps your Angular app for the browser, and since it already includes CommonModule, you don’t need to import CommonModule separately. Example:
@NgModule({ declarations: [AppComponent], imports: [BrowserModule, AppRoutingModule], // BrowserModule for root providers: [], bootstrap: [AppComponent] }) export class AppModule { }
For Feature/Lazy-Loaded Modules
Never import BrowserModule here—stick with CommonModule. This gives your module access to all the core directives and pipes without causing singleton service conflicts. Example:
@NgModule({ declarations: [ProductListComponent, ProductDetailComponent], imports: [CommonModule, ProductRoutingModule], // CommonModule for features exports: [ProductListComponent] }) export class ProductsModule { }
Common Mistake to Avoid
A lot of new Angular devs accidentally import BrowserModule in feature modules, which leads to errors like "Provider already exists in the injector". This happens because BrowserModule registers some singleton services that should only exist once in your app. Stick to CommonModule for all non-root modules, and you’ll avoid this headache.
内容的提问来源于stack exchange,提问作者Pritam Bohra

