DEV Community

Cover image for Understanding NestJS Modules
Tasfia Islam
Tasfia Islam

Posted on

5

Understanding NestJS Modules

What is a module?

In NestJS, a module is a class which helps to organize other building blocks of the application like components, services etc. maintaining modularity with separate concerns.

Modules serve several key purposes in NestJS development.

Each module provides encapsulation and isolation to a closely related set of capabilities. This isolation helps to avoid naming conflicts and provides an effective way to organize the components.

A module class define providers and inject them into other components leveraging Dependency Injection.

Modules create way of reusability and scalability across the components and across projects and can also be nested within other modules creating a hierarchical structure.

An example module

Let's create a basic Module.

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

In this example UserModule encapsulates the UserService and UserController.

Seems confusing? Let's break down the parts of the module.

Breakdown of a module

decorators
We use the @Module decorator to create a module which takes a single object defining the module's properties.

providers
The provider that can be shared across other parts of the application and handles specific business logic and consists of service and other reusable components.

controllers
The set of Controllers which define end points and route handlers.

imports
The list of imported modules that export the providers required in this module.

exports
Modules export components available to be used outside the module.

Conclusion

Modules are the backbone of a reusable and well structured NestJS application enabling us to create well-organized, scalable and modular codebases. This was a brief introduction to modules.

Read more from the official documentation

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay