In NestJS, dynamic modules enable the dynamic registration of modules, providers, or controllers based on varying conditions. This flexibility is particularly valuable for developing services with differentiated behavior based on configuration or environment variables.
To register dynamic modules in NestJS using registerSync, we typically utilize static methods of the module, such as forRoot or forRootSync, to synchronously register the module and its related dependencies. These methods usually return a dynamic module object containing the module property pointing to the current module, as well as providers and exports properties listing the providers to be registered and exported.
Here is a typical example. Suppose we have a configuration module ConfigModule that can synchronously receive configuration options, and we want to dynamically register this module into our application.
typescript// config.module.ts import { Module, DynamicModule, Global } from '@nestjs/common'; import { ConfigService } from './config.service'; @Global() @Module({}) export class ConfigModule { static registerSync(options: ConfigOptions): DynamicModule { const providers = [ { provide: ConfigService, useValue: new ConfigService(options), }, ]; return { module: ConfigModule, providers: providers, exports: providers, // Add ConfigService to the exports list so that other modules can inject it }; } }
In the above code, ConfigModule synchronously receives configuration options and registers them via the registerSync method. ConfigService is an example service that utilizes these configurations.
Then, in the root module of the application, we can import ConfigModule into the application using the ConfigModule.registerSync method and pass the required configuration options. Here is how to register it:
typescript// app.module.ts import { Module } from '@nestjs/common'; import { ConfigModule } from './config/config.module'; @Module({ imports: [ ConfigModule.registerSync({ // Configuration options }), ], // ... other modules and providers }) export class AppModule {}
In this example, we synchronously pass the configuration options to ConfigModule and register it as a dependency into the application module AppModule. This way, we can use the ConfigService service throughout the application and access the configuration options.