0
0
NestJSframework~5 mins

Why modules organize application structure in NestJS

Choose your learning style9 modes available
Introduction

Modules help keep your NestJS app neat and tidy. They group related parts together so your code is easier to find and manage.

When your app grows and you want to keep features separated.
When you want to share code between different parts of your app.
When you want to make your app easier to test and maintain.
When you want to clearly define boundaries between features.
When you want to load parts of your app only when needed.
Syntax
NestJS
import { Module } from '@nestjs/common';

@Module({
  imports: [],
  controllers: [],
  providers: [],
  exports: [],
})
export class YourModule {}

The @Module decorator defines a module.

You list controllers, providers, and other modules inside the decorator.

Examples
This module groups the cat-related controller and service together.
NestJS
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}
This module imports another module to use its features.
NestJS
import { Module } from '@nestjs/common';
import { DatabaseModule } from './database.module';

@Module({
  imports: [DatabaseModule],
})
export class AppModule {}
Sample Program

This example shows a simple module grouping a controller and a service. The controller uses the service to return a greeting.

NestJS
import { Module, Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
class HelloService {
  getHello(): string {
    return 'Hello from service!';
  }
}

@Controller()
class HelloController {
  constructor(private readonly helloService: HelloService) {}

  @Get()
  sayHello(): string {
    return this.helloService.getHello();
  }
}

@Module({
  controllers: [HelloController],
  providers: [HelloService],
})
export class HelloModule {}
OutputSuccess
Important Notes

Modules help you organize code by feature or functionality.

They make your app easier to understand and maintain.

Use the imports array to bring in other modules.

Summary

Modules group related code to keep your app organized.

They define clear boundaries between parts of your app.

Using modules makes your app easier to manage and scale.