Search code examples
visual-studio-codenestjsmonoreponomachine-nx

How do I generate a NestJS resource in an app within an Nx workspace using the nx cli?


I want to generate a NestJS resource in my new nestjs app within an Nx workspace, similar to the way you would in a solo NextJS app using the nest generate cli command. Using the nx generate command I would expect to have to specify the app you want the resource added to, like:

nx generate @nestjs/schematics:resource **--app=haida-stories-api** --name=testresource

I tried the VS Nx Console but there are no options to specify the app target for the generate command. When I add a resource without tweaking any of the other options it just creates a new src directory in the root dir of the workspace and creates a resource unrelated to any app.

The --sourceRoot option in VS Nx Console allows me to manually enter the path to the source directory I want, but it doesn't automatically add the correct imports to the main app module.

Using the nx generate command on the command line rather than in Nx Console in VS, you can add the “project” argument:

nx g @nrwl/nest:resource <resource-name> project <app-name>

This command does generate the controller in the correct project src directory, but it doesn’t edit the app module.ts file to add the file import statement and add the resource module to the imports array, making it a route in the app.

In a pure NestJS app, if I run the following nest cli command, it automatically edits the module file:

nest generate controller test

Am I missing some documentation on the Nx cli and how it works using the VS Nx Console?


Solution

  • projects/api is the folder so you need to be more specific. Also be warned it added files not a folder + files.

    nx generate @nx/nest:resource [NAME] --directory projects/api/[NAME]
    

    Easier to use NX tools and the generator > generate > @nx/nest resource