Understanding Modules
Learn how to create and organize modules in a NestJS application.
We'll cover the following
In NestJS, modules help organize and structure code by grouping related components. Each module represents a distinct and self-contained unit of functionality within an application. For example, a module might be responsible for handling user authentication or managing database connections. Additionally, developers can easily reuse modules across different parts of an application or share them between multiple applications, making modules a flexible and scalable solution for building complex systems.
Modules in NestJS
The @Module()
decorator helps define a module. It takes an object that might contain several properties to configure the module. These properties can include controllers
, providers
, imports
, and exports
.
controllers
: Thecontrollers
property in the@Module
decorator defines the set of controllers that belong to the module.providers
: Theproviders
property defines a set of objects, such as services and repositories, that components within the same module can inject and use.imports
: Theimports
property refers to othermodules
required for the module to work. They can includemodules
from NestJS, third-party modules, or other modules in the application.exports
: The@Module()
decorator uses theexports
property to makeproviders
from the currentmodule
available to othermodules
that import it. By exportingproviders
, differentmodules
can use them without redefining them, reducing duplication, and improving code organization.
Get hands-on with 1400+ tech skills courses.