DEV Community

Denis Morozov
Denis Morozov

Posted on

Demystifying Nx's "dependsOn" configuration

We're using Nx in our multirepos to build our Node/Nest apps, as well as Angular. It was a long story how we migrated from Angular Workspace repo for web apps, and single repos for NodeJS/Nest, but in this article I'd like to focus on "dependsOn" property of project.json and how we treat it.

Nx documentation contains a good portion of "dependsOn" description - https://nx.dev/reference/project-configuration#dependson but as for me it still not clear how does "dependsOn" inside "targetDefaults" interact with project-level "dependsOn".

In our project we're utilizing some shared libraries which can be used for Angular apps and for NodeJS/Nest apps as well, i.e. some models definitions and so on. Thus, it is important that those libraries should be built before other apps. That's why we included libraries definitions into "targetDefaults". From other hand we have got some script which need to be run before build, so we create a separate task inside project.json to describe it.

 "injectBuildVersion": {
   "executor": "nx/run-script",
   "options": {
     "script": "inject-build-version some-app"
   }
 }
 "targetDefaults": {
   "build": {
     "dependsOn": "some-lib"
   }
 },
 "dependsOn": ["injectBuildVersion"]
Enter fullscreen mode Exit fullscreen mode

as a result the application was failing to build, because library wasn't built yet. But we noticed that "injectBuildVersion" was executing correctly.

The reason of such behavior is that project-level "dependsOn" overrides "targetDefaults". Moreover, this behavior already described somewhere in Nx issues :-) To make it work, we have to include a special dependency "^build" into project-level "dependsOn" property, like this:

 "injectBuildVersion": {
   "executor": "nx/run-script",
   "options": {
     "script": "inject-build-version some-app"
   }
 }
 "targetDefaults": {
   "build": {
     "dependsOn": "some-lib"
   }
 },
 "dependsOn": ["injectBuildVersion", "^build"]
Enter fullscreen mode Exit fullscreen mode

Now, everything works as expected, build version value (which comes from Jenkins) injects into environment.ts file, and then Nx performs the build with all necessary dependencies. Good job, Nx!

Top comments (1)

Collapse
 
kasir-barati profile image
Mohammad Jawad (Kasir) Barati

Hi, thanks for the post. Just wanna let you know that I usually tend to list dependencies in each script's dependsOn array at the project level. And on another note, please use some form of title for the configs since right now it is really hard to distinguish which is which. At least I cannot do it and as of now this configs look to me a lot like gibberish 😅.