Search code examples
nrwl-nxnx-monorepo

How run custom command ( run bash script ) before NX command?


I would like to execute a .sh script before running the "serve" command. Is there an option in Nx similar to "before"?

So, I want to run a bash script when I execute npx nx run projectName:storybook or projectName:serve, before the main command starts.

 "projectName": {
      "root": "path/testPath",
      "sourceRoot": "path/testPath",
      "projectType": "application",
      "targets": {
        "serve": {
           ...
          },
          "configurations": {
             ...
          },
          "before": ["nx run testTest:alex"]
        },
        "storybook": {
          "executor": "@nrwl/storybook:storybook",
          "options": { 
            ...
          },
          "configurations": {
            "ci": {
              "quiet": true
            }
          },
          "before": ["nx run testTest:alex"]
        },

Solution

  • All targets support a dependsOn property (see docs). This will ensure that another target is run before your target starts up.

    "targets": {
       "serve": {
          "exectuor": "@nx/whatever",
          "dependsOn": ["some-other-target"],
          //...
       },
    
       "some-other-target": {
          "command": "./path/to/some/script.sh"
       }
    }
    

    With this setup NX will run nx run my-project:some-other-target first when nx run my-project:serve is called.


    Alternatively, you could move the serve target to some other name, and make a new serve target that runs the commands you need.

    Perhaps like:

    "targets": {
       "serve": {
          "executor": "nx:run-commands",
          "options": {
             "commands": [
                "nx run my-app:some-other-target"
                "nx run my-app:serve-web",
             ],
             "parallel": false
          }
       },
    
       "serve-web": {
          "exectuor": "@nx/whatever",
          //...
       },
    
       "some-other-target": {
          "command": "./path/to/some/script.sh"
       }
    }
    

    Now serve is a target that invokes two other targets in a specific order.