Skip to main content

103. Modules

Modules

  • Modules | NestJS - A progressive Node.js framework
  • Modules are a fundamental building block in Nest.js.
    • They organize the application into cohesive units, encapsulating related functionality.
    • Each module has its own context and can define providers, controllers, and other related components.
    • Modules help with code organization, reusability, and separation of concerns.
ng g module module_name

Part of Nest Module

@Module({
imports: [ConfigModule, DatabaseModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
  • imports
    • The imports property is used to import other modules that the current module depends on.
  • controllers:
    • The controllers property is where you define the controllers for handling incoming HTTP requests and defining routes.
  • providers:
    • The providers property is where you define the providers (services) required by the module.
  • exports:
    • The exports property specifies the components (controllers, services, etc.) that are accessible to other modules.
    • It allows you to expose functionality from the current module to be used in other parts of your application.
//for instance if you want to use the above exported users-service in orders-module, you would do something like

@Module({
imports: [UsersModule, BillingModule], <-------
controllers: [OrdersController],
providers: [OrdersService],
exports: [],
})
export class OrdersModule {}

//now you can use users-service inside order-modules(controller, services...)

Module Import Precedence

  • the first module in an import array will be loaded first before the second module in the array.
    • this mean other modules that depends on X module, need to come after X module
imports: [
ConfigModule, //loads config for db to use -> loads first
TypeOrmModule.forRoot(...) //connects to db with above config -> loads second
]

To prevent this behavior we can configure asynchronous dynamic modules…

Dynamic Modules

providers: [
DBModule.register({
name: 'postgresql',
password: 'pass',
port: 3360
})
]