typescriptnestjs

How To Specify Which Module to add Controller to in NestJS CLI?


Ive been playing with NestJS for about a week. So far, Im really liking it. The Module system is great. And, I love how easy it is to do things like parse requests.

One question I do have is with regards to the NestJS CLI.

Suppose I have multiple modules. I can create a controller with the following command.

nest g controller Accounts

How do I specify which module this controller belongs to?

The CLI seems to default to the last module you created.

How do I change this behavior?


Solution

  • The CLI, to my knowledge, will see if you have any modules that match the name of the controller you are creating. For example, if you run

    nest g mo accounts
    nest g mo contacts
    nest g mo leads
    

    And then you run the same for controllers, but in a different order, like

    nest g co leads
    nest g co accounts
    nest g co contacts
    

    You'll still get the AccountsController in the AccountsModule, the LeadsController in the LeadsModule, and the ContactsController in the ContactsModule

    If you are looking to add a specific controller to a module that is named differently than the Controller (i.e. add the LeadsController to the AccountsModule) you can pass a path option as the final parameter to the CLI e.g.

    nest g co leads accounts
    

    The path you give is relative to src (or whatever your root directory is in the nest-cli.json). This will create the directory accounts/leads where the leads.controller.ts file will live, and will add the controller to the AccountsModule.

    The reason that Nest adds the new class to the module of the same name by default is to allow for easy feature module development. The need to not specify the module makes the CLI usage much more friendly to developers (usually), and as a fallback, if a module cannot be found, the CLI adds it to the AppModule (or whatever you have the root module called).