DEV Community

Cover image for NestJS: Modules
Ilya R
Ilya R

Posted on

NestJS: Modules

Modules are isolated parts of a NestJS application. Thanks to the modular system, you can easily expand the functionality of the application. Also, isolation makes it easier to debug code and keeps it cleaner. But, isolation can bring some difficulties.

In NestJS, you can create a module using the CLI

nest g module products

A module is a class wrapped in @Module decorator which is imported from '@nestjs/common'. Many applications written in NestJS use many modules, but there must be at least one - the root module.

The @Module decorator passes certain metadata and takes an object with properties as an argument:

  • imports - list of imported modules - using this property, you can create a convenient structure of modules in the application;
  • controllers - a list of controllers that are used only in this module;
  • providers — providers used in this module;
  • exports - part of the providers used in this module, but which may be available in other parts of the application.
import { Module } from '@nestjs/common';

import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService],
})
export class ProductsModule {}
Enter fullscreen mode Exit fullscreen mode

Every new module must be imported into the root App module in order for it to be available in the application.

// app.module.ts

import { Module } from '@nestjs/common';

import { ProductsModule } from './products/products.module';

@Module({
  imports: [ProductsModule ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Also, in NestJS it is possible to create a global module that can be used throughout the application. For this purpose, you need use the @Global decorator. This module must be registered once in the root module and can be used in all application.

import { Module, Global } from '@nestjs/common';

import { CommonService } from './common.service';
import { CommonController } from './common.controller';


@Global()
@Module({
  controllers: [CommonController],
  providers: [CommonService],
})
export class CommonModule {}
Enter fullscreen mode Exit fullscreen mode

The main thing to understand is that Modules are parts of an application. Their purpose is to encapsulate and isolate these parts within themselves. For example, for the Product module, we can use ProductController and ProductService - they will include all the code related only to the Product module and will work with a specific entity. As for me, it would be convenient to create modules according to the entities from app's database.

Thanks for your time!

Discussion (0)