Performance: Global modules
Global modules affect the initial load time and memory usage by making services available app-wide without repeated imports.
import { Global, Module } from '@nestjs/common'; @Global() @Module({ providers: [SharedService], exports: [SharedService], }) export class SharedModule {} @Module({ imports: [SharedModule], }) export class AppModule {}
import { ModuleA } from './module-a'; import { ModuleB } from './module-b'; @Module({ imports: [ModuleA, ModuleB], }) export class AppModule {}
| Pattern | Module Imports | Service Instantiations | Bundle Size Impact | Verdict |
|---|---|---|---|---|
| Repeated imports of shared services | Multiple | Multiple | Larger | [X] Bad |
| Global module with shared services | Single global import | Single | Smaller | [OK] Good |
@Global() in NestJS?@Global()@Global() decorator marks a module so its providers can be used app-wide without importing it in every module.@Global() is used above the module class to mark it global.@Global() and @Module() with providers and exports arrays.@Global()
@Module({
providers: [ConfigService],
exports: [ConfigService],
})
export class ConfigModule {}ConfigModule again?@Global()
@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}LoggerService in another module, you get an error: Nest can't resolve dependencies. What is the likely cause?@Injectable(), NestJS cannot inject it, causing the error.@Injectable() to LoggerService -> Option D@Global(), export the service, and import it only once in the root module -> Option APass the test and this pattern moves unknown