Search code examples
nestjs

Advantages of using @Module NestJS


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.


Solution

  • The modules in NestJS are inspired by Angular. Whereas, Angular added the module system because of lazy loading: Modules: when and why?. This makes sense, SPA apps are notorious for heaviness.

    And at this point, we need to ask one question. Does NestJS need the lazy load?

    The answer is no. There is no such thing as lazy load on backend applications. Maybe in the world, we can find some cases where lazy load is needed on the backend, but I can't recall anything.

    Yes, you can put everything into AppModule. Really. There is absolutely no need for multiple modules.

    And yes, you are right, organizing code by folders is enough.