Skip to content

Instantly share code, notes, and snippets.

@andersonba
Last active July 26, 2022 07:35
Show Gist options
  • Save andersonba/3665222e8bb2e73937276b7d96172211 to your computer and use it in GitHub Desktop.
Save andersonba/3665222e8bb2e73937276b7d96172211 to your computer and use it in GitHub Desktop.
An Nx executor to run a target in parallel across all project dependencies, also forwarding the args to the commands.
import { ExecutorContext, readCachedProjectGraph } from '@nrwl/devkit'
import runCommandsExecutor from 'nx/src/executors/run-commands/run-commands.impl'
import { RunDepsExecutorSchema } from './schema'
function getForwardedArgs(): string[] {
try {
const nxCommandArg = JSON.parse(process.argv[2] || '{}') as {
overrides?: {
__overrides_unparsed__?: string[]
}
}
return nxCommandArg?.overrides?.__overrides_unparsed__ || []
} catch (err) {
console.error(err)
return []
}
}
export default async function runExecutor(schema: RunDepsExecutorSchema, context: ExecutorContext) {
schema = {
forwardAllArgs: true,
...schema,
}
const projectName = schema.project || context.projectName
if (!projectName || !context.workspace.projects[projectName]) {
throw new Error(`No project "${projectName}" found`)
}
const graph = readCachedProjectGraph()
const projectsToRun = []
for (const d of graph.dependencies[projectName]) {
const depTargets = graph.nodes[d.target]?.data.targets || {}
if (schema.target in depTargets) {
projectsToRun.push(d.target)
}
}
return runCommandsExecutor(
{
commands: projectsToRun.map((project) => ({
command: `nx run ${project}:${schema.target}`,
forwardAllArgs: schema.forwardAllArgs,
})),
parallel: true,
color: true,
__unparsed__: getForwardedArgs(),
},
context
)
}
export interface RunDepsExecutorSchema {
target: string
project?: string
forwardAllArgs?: boolean
}
{
"$schema": "http://json-schema.org/schema",
"cli": "nx",
"title": "Run dependencies target",
"description": "",
"type": "object",
"properties": {
"target": {
"type": "string"
},
"project": {
"type": "string"
},
"forwardAllArgs": {
"type": "boolean",
"default": true
}
},
"required": ["target"]
}
@andersonba
Copy link
Author

Example of project.json:

{
  "targets": {
    "codegen": {
      "executor": "@my-org/nx-tools:run-deps",
      "options": {
        "target": "codegen"
      }
    },
    "serve-and-watch": {
      "executor": "@nrwl/workspace:run-commands",
      "options": {
        "parallel": true,
        "commands": [
          {
            "command": "nx run my-app:serve",
            "forwardAllArgs": true
          },
          {
            "command": "nx run my-app:codegen --watch"
          }
        ]
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment