Careeroza
What is a Module
The @Module Decorator
A module is a class with the @Module() decorator. It tells NestJS which controllers and providers belong together. Every app has one root module (AppModule), and NestJS builds the whole app by walking through its imports.
| Property | Meaning |
|---|---|
controllers | Controllers of this module (NestJS creates them and maps their routes) |
providers | Services and other injectables created in this module |
imports | Other modules whose exported providers this module needs |
exports | Providers from this module that importing modules may use |
How NestJS Reads Modules
Example
NestJS walks the module tree from the root and registers every module once, even if it is imported many times. This plain TypeScript version shows that walk:
interface ModuleDef {
name: string;
imports: ModuleDef[];
providers: string[];
}
const DatabaseModule: ModuleDef = { name: 'DatabaseModule', imports: [], providers: ['DataSource'] };
const UsersModule: ModuleDef = { name: 'UsersModule', imports: [DatabaseModule], providers: ['UsersService'] };
const ProductsModule: ModuleDef = { name: 'ProductsModule', imports: [DatabaseModule], providers: ['ProductsService'] };
const OrdersModule: ModuleDef = { name: 'OrdersModule', imports: [DatabaseModule, UsersModule, ProductsModule], providers: ['OrdersService'] };
const AppModule: ModuleDef = { name: 'AppModule', imports: [ProductsModule, OrdersModule], providers: [] };
const seen = new Set<ModuleDef>();
function scan(mod: ModuleDef, depth: number): void {
if (seen.has(mod)) {
console.log(' '.repeat(depth) + mod.name + ' (already loaded)');
return;
}
seen.add(mod);
console.log(' '.repeat(depth) + mod.name + ' [' + mod.providers.join(', ') + ']');
for (const child of mod.imports) scan(child, depth + 1);
}
scan(AppModule, 0);
console.log('modules initialized:', seen.size);Output
AppModule []
ProductsModule [ProductsService]
DatabaseModule [DataSource]
OrdersModule [OrdersService]
DatabaseModule (already loaded)
UsersModule [UsersService]
DatabaseModule (already loaded)
ProductsModule (already loaded)
modules initialized: 5