Advantages of using @Module NestJS

Viewed 165

I'm making a new NestJS app and after a lot of errors on the first because the multiple modules I created didn't have the correct imports, providers, exports, TypeOrmModule.forFeature etc made me wonder: What was the point?

Why not use only the app.module and just dump everything in it? All the controllers and services and entity types and any other that may come up?

From the documentation:

We want to emphasize that modules are strongly recommended as an effective way to organize your components

Is that the only reason? Organization? Does dependency injection play a role of some kind?

Edit:

If organization is the main reason, why not separate in a different folder with a controller and service? Basically a module without the imports, providers etc. Doing the same thing with less boilerplate.

1 Answers

Why not use only the app.module and just dump everything in it?

Better yet, why use multiple files at all? Why not just have a couple thousand line index.js with no types, no organization, just raw JS all the way down?

The answer? Code organization and ease of re-use. By making these modules, you should be grouping together similar logic together. All the code for a single feature should be available by just importing FeatureModule and usable. When it comes to library modules, this becomes pretty apparent: TypeOrmModule has a forRoot/forRootAsync and a forFeature which exposes ways to inject repositories into your services. The JwtModule has a register/registerAsync and exposes a JwtService so you can configure the JwtService once and re-use the provider.

When dealing with entity features this may look messier, but technically it's all still possible, so that in theory you'd be able to take FeatureModule from Application A and drop it into Application B and have everything still working with regards to the FeatureModule, similar to how pulumi has the idea of stacks and applications and you can just spin up new applications using the same group of components.

The module system, once you get the hang of it, and in my opinion, makes it very easy to recognize what all a module will be working with, with regards to other features and how they're connected. It's just a matter of discipline and learning the feature of the framework.

Related