In NestJS, why would you use module re-exporting?
Think about how to share services without importing every module everywhere.
Module re-exporting lets a module export providers it imports, so other modules can access them by importing only the re-exporting module.
Given the following NestJS modules, what will happen when AppModule injects SharedService?
import { Module, Injectable } from '@nestjs/common'; @Injectable() export class SharedService { getMessage() { return 'Hello from SharedService'; } } @Module({ providers: [SharedService], exports: [SharedService], }) export class SharedModule {} @Module({ imports: [SharedModule], exports: [SharedModule], }) export class CoreModule {} @Module({ imports: [CoreModule], }) export class AppModule { constructor(private sharedService: SharedService) {} getMessage() { return this.sharedService.getMessage(); } }
Consider how exports and imports work in NestJS modules.
CoreModule imports and re-exports SharedModule, which exports SharedService. AppModule imports CoreModule, so it can inject SharedService successfully.
Which of the following code snippets correctly re-exports SharedModule inside CoreModule?
Remember that to re-export a module, it must be both imported and exported.
To re-export a module, you must list it in both imports and exports arrays of the @Module decorator.
Consider these modules:
import { Module, Injectable } from '@nestjs/common';
@Injectable()
export class ServiceA {}
@Module({
providers: [ServiceA],
})
export class ModuleA {}
@Module({
imports: [ModuleA],
exports: [ModuleA],
})
export class ModuleB {}
@Module({
imports: [ModuleB],
})
export class AppModule {
constructor(private serviceA: ServiceA) {}
}Why does NestJS throw a runtime error that ServiceA is not available in AppModule?
Check what each module exports and imports.
ModuleA provides ServiceA but does not export it. ModuleB imports and exports ModuleA, but since ServiceA is not exported by ModuleA, it is not available to ModuleB or AppModule.
Given these modules and service, how many instances of SingletonService will be created when AppModule injects it?
import { Module, Injectable } from '@nestjs/common';
@Injectable()
export class SingletonService {
id = Math.random();
}
@Module({
providers: [SingletonService],
exports: [SingletonService],
})
export class SharedModule {}
@Module({
imports: [SharedModule],
exports: [SharedModule],
})
export class CoreModule {}
@Module({
imports: [CoreModule, SharedModule],
})
export class AppModule {
constructor(public coreService: SingletonService, public sharedService: SingletonService) {}
}How many different instances of SingletonService exist in AppModule?
Think about how NestJS handles singleton providers across modules.
Even though SharedModule is imported twice (directly and via CoreModule), NestJS creates only one instance of SingletonService because providers are singletons within the application context.