You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Nx使run-commands默认从项目根目录执行任务?

解决Nx monorepo中make任务重复配置cwd的问题

核心问题

使用nx:run-commands短格式配置时,任务会在工作区根目录执行,导致make找不到项目内的Makefile;长格式配置需要手动指定cwd,但每个项目重复配置过于冗余。

可行解决方案

1. 复用内置变量${projectRoot}

Nx提供内置变量${projectRoot},可直接在cwd中引用,无需硬编码项目路径,简化配置:

"targets": {
    "test": {
        "executor": "nx:run-commands",
        "options": {
            "command": "make test",
            "cwd": "${projectRoot}"
        }
    },
    "build": {
        "executor": "nx:run-commands",
        "options": {
            "command": "make build",
            "cwd": "${projectRoot}"
        }
    }
}

这种方式无需修改路径,复制配置时只需调整command即可,减少重复工作量。

2. 自定义执行器封装默认cwd

创建一个自定义执行器,自动将cwd设置为当前项目根目录,避免每个target重复配置:

  • 在tools/executors/make-runner目录下创建执行器文件:
    executor.ts:
    import { ExecutorContext } from '@nx/devkit';
    import { runExecutor } from '@nx/workspace/src/executors/run-commands/run-commands.impl';
    
    export interface MakeRunnerOptions {
      command: string;
    }
    
    export default async function runExecutor(
      options: MakeRunnerOptions,
      context: ExecutorContext
    ) {
      return runExecutor(
        {
          ...options,
          cwd: context.projectRoot,
        },
        context
      );
    }
    
  • 在nx.json中注册该执行器:
    "executors": {
      "tools:make-runner": "tools/executors/make-runner"
    }
    
  • 项目中使用自定义执行器,无需指定cwd:
    "targets": {
        "test": {
            "executor": "tools:make-runner",
            "options": {
                "command": "make test"
            }
        }
    }
    

3. 使用project.json继承模板

创建通用的make项目配置模板,让所有非JS项目继承,统一管理配置:

  • 在工作区根创建模板文件templates/make-project/project.json:
    {
      "targets": {
        "test": {
          "executor": "nx:run-commands",
          "options": {
            "command": "make test",
            "cwd": "${projectRoot}"
          }
        },
        "build": {
          "executor": "nx:run-commands",
          "options": {
            "command": "make build",
            "cwd": "${projectRoot}"
          }
        }
      }
    }
    
  • 每个make项目的project.json继承该模板,如需个性化配置可直接覆盖:
    {
      "extends": "../../templates/make-project/project.json",
      // 项目专属配置...
    }
    

补充说明

目前Nx暂不支持在单个项目的project.json中设置所有target的默认选项(类似全局targetDefaults的项目级版本),上述方案均为针对该场景的实用替代方案。

内容的提问来源于stack exchange,提问作者amnesia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:37:03