Performance: Shared modules
This affects the initial load time and memory usage by controlling how code is reused across the app.
import { CommonService } from './common.service'; import { Module } from '@nestjs/common'; @Module({ providers: [CommonService], exports: [CommonService] }) export class SharedModule {} @Module({ imports: [SharedModule], }) export class FeatureModule {} @Module({ imports: [SharedModule], }) export class AnotherFeatureModule {}
import { CommonService } from './common.service'; import { Module } from '@nestjs/common'; @Module({ providers: [CommonService], exports: [CommonService] }) export class FeatureModule {} @Module({ imports: [FeatureModule], providers: [CommonService], // duplicated provider }) export class AnotherFeatureModule {}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Duplicated providers in multiple modules | N/A | N/A | N/A | [X] Bad |
| Single shared module providing common services | N/A | N/A | N/A | [OK] Good |
Shared Module in NestJS?exports array of the module decorator.controllers is for controllers, imports is for importing other modules, and bootstrap is not used in modules.exports array in the module decorator -> Option AAppModule injects CommonService and calls getMessage()?
import { Module } from '@nestjs/common';
import { CommonService } from './common.service';
@Module({
providers: [CommonService],
exports: [CommonService],
})
export class SharedModule {}
// CommonService
export class CommonService {
getMessage() {
return 'Hello from SharedModule';
}
}
// AppModule
import { Module } from '@nestjs/common';
import { SharedModule } from './shared.module';
@Module({
imports: [SharedModule],
})
export class AppModule {
constructor(private commonService: CommonService) {}
printMessage() {
console.log(this.commonService.getMessage());
}
}
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';
@Module({
providers: [LoggerService],
imports: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}imports array is for importing other modules, not providers or services.providers and exports, but not in imports.FeatureModule and SharedModule. SharedModule exports UtilityService. You want FeatureModule to use UtilityService and also export it for other modules. How should you configure FeatureModule to achieve this?exports array.Pass the test and this pattern moves unknown