Nx Plugin Executor 生成器完全指南:从零创建与自定义你的 Nx Executor
Nx Plugin Executor 生成器完全指南:从零创建与自定义你的 Nx Executor
本篇指南以 @nx/plugin:executor 生成器为核心,结合 Nx 仓库(Monorepo Platform)中该生成器的完整源码实现,系统讲解如何在 Nx Plugin 项目中创建 Executor。你将掌握四种典型生成方式(基础用法、省略扩展名、自定义导出名、启用自定义 Hasher),理解生成器在底层创建了哪些文件、如何注册进 executors.json,并学会如何根据实际需求选择正确参数。
前置条件:在 Nx Plugin 项目中准备生成环境
@nx/plugin:executor 生成器依赖一个已存在的 Nx Plugin 项目(即 package.json 中存在 executors/builders 字段并配套 executors.json 的库项目)。若尚未创建插件项目,可先通过 @nx/plugin:plugin 生成器创建,其生成逻辑在仓库的 plugin 生成器 中实现。
生成器采用交互式命令行设计,核心路径参数 path 通过 "x-priority": "important" 标记为必填(见 schema.json)。运行 nx g @nx/plugin:executor 时若省略参数,CLI 会进入交互提示引导输入。
基础用法:生成一个名为 build 的 Executor
创建名为 build 的 Executor,文件落位于 tools/my-plugin/src/executors/build.ts:
nx g @nx/plugin:executor tools/my-plugin/src/executors/build.ts
从仓库源码 executor.ts 可以看出,执行该命令后生成器依次完成三件事:
- 规范化路径与命名(
normalizeOptions):通过determineArtifactNameAndDirectoryOptions解析出name(工件名)、directory(目标目录)、fileName(文件基名)与project(所属项目)。 - 生成模板文件(
addFiles):调用generateFiles把 files/executor 下的模板渲染到目标目录。 - 注册 Executor(
updateExecutorJson):把新 Executor 写进插件的executors.json,并自动向package.json注入@nx/devkit依赖。
执行后会得到如下文件结构(生成器测试 executor.spec.ts 对此有明确断言):
tools/my-plugin/src/executors/
├── build.ts # Executor 实现
├── build.spec.ts # 单元测试
├── schema.json # 选项 JSON Schema
└── schema.d.ts # 选项 TypeScript 类型
其中 build.ts 由模板 fileName.ts.template 渲染而来:
import type { PromiseExecutor } from "@nx/devkit";
import type { BuildExecutorSchema } from './schema';
const runExecutor: PromiseExecutor<BuildExecutorSchema> = async (options) => {
console.log('Executor ran for Build', options);
return {
success: true
};
}
export default runExecutor;
模板中的 className(如 Build)来自文件名驼峰化处理,PromiseExecutor<Schema> 是 Nx Devkit 提供的类型,规定 Executor 必须返回包含 success 字段的 Promise<{ success: boolean }>,Nx 据此判断任务是否成功。
build.spec.ts 由模板 fileName.spec.ts.template 渲染,默认使用 Jest,构造了一个最小的 ExecutorContext 并断言 output.success === true,可直接运行 nx test 验证。
生成的 schema 文件
Executor 的选项由 schema.json 定义,生成器默认产出如下骨架(见 schema.json.template):
{
"$schema": "https://json-schema.org/schema",
"version": 2,
"title": "Build executor",
"description": "",
"type": "object",
"properties": {},
"required": []
}
同时生成 schema.d.ts,定义 BuildExecutorSchema 类型供实现与测试引用。你需要按需在 properties 中补充选项定义,并在 .d.ts 中同步类型,Nx 会以该 Schema 对 CLI 传入的 options 做运行时校验与默认值补全。
省略文件扩展名:利用路径推断
创建同名 Executor,但 path 不带 .ts 扩展名:
nx g @nx/plugin:executor tools/my-plugin/src/executors/build
两种写法生成的产物完全一致(源码测试 executor.spec.ts 分别对带扩展名与不带扩展名的 path 进行了验证,结果一致)。其原理在 normalizeOptions 中实现:
const knownFileExtensions = ['.ts', '.js', '.jsx', '.tsx'];
const hasKnownFileExtension = knownFileExtensions.some((ext) =>
lastSegment.endsWith(ext)
);
if (!hasKnownFileExtension && lastSegment === name) {
directory = joinPathFragments(initialDirectory, name);
}
(见 executor.ts)生成器通过两个启发式规则智能判断路径语义:
- 路径最后一段带已知扩展名(
.ts、.js、.jsx、.tsx)时,按文件路径处理,工件直接落在该目录; - 最后一段恰好等于工件名且无扩展名时,判定传入的是目录路径,会自动把工件名追加为子目录,即
tools/my-plugin/src/executors/build/下生成build.ts。
这与 @nx/plugin:executor 内部使用 Nx Devkit 的 determineArtifactNameAndDirectoryOptions(allowedFileExtensions: ['ts'])的解析规则一致。建议在脚本与 CI 中统一使用带扩展名的写法,路径语义最明确。
自定义导出名称:--name=custom
若 Executor 文件名与注册名不同,通过 --name 指定 executors.json 中注册的键名:
nx g @nx/plugin:executor tools/my-plugin/src/executors/build.ts --name=custom
生成文件仍为 build.ts,但注册在 executors.json 中的名称是 custom。底层实现见 executor.ts,注册逻辑如下:
executors[options.name] = {
implementation: `${dir}/${options.fileName}`,
schema: `${dir}/schema.json`,
description: options.description,
};
if (options.includeHasher) {
executors[options.name].hasher = `${dir}/hasher`;
}
即 implementation 始终指向实际生成的 fileName 文件,而键名 executors[options.name] 采用 --name 的值。于是运行任务时使用 nx run <project>:custom 即可调用 build.ts 中的实现。当你不指定 --name 时,name 默认由 path 推导,且 description 默认为 ${name} executor。
name 参数在 schema.json 中为非必填字段,其描述为 “The executor name to export in the plugin executors collection”,即它控制的正是 executors.json 中的导出键名。
自定义 Hashing:--includeHasher
若需要对任务的缓存 Hash 计算做定制,使用 --includeHasher 额外生成 Hasher 样板代码:
nx g @nx/plugin:executor tools/my-plugin/src/executors/build --includeHasher
生成器检测到 includeHasher 后,会额外调用 addHasherFiles(见 executor.ts),从 files/hasher 渲染出 hasher.ts 与 hasher.spec.ts,并在注册时把 hasher: "${dir}/hasher" 写入 executors.json。生成目录结构为:
tools/my-plugin/src/executors/build/
├── build.ts
├── build.spec.ts
├── hasher.ts # 自定义 Hasher 实现
├── hasher.spec.ts # Hasher 单元测试
├── schema.json
└── schema.d.ts
hasher.ts 的样板实现(见 hasher.ts.template)如下:
import type { CustomHasher } from '@nx/devkit';
/**
* This is a boilerplate custom hasher that matches
* the default Nx hasher. If you need to extend the behavior,
* you can consume workspace details from the context.
*/
export const buildHasher: CustomHasher = async (task, context) => {
return context.hasher.hashTask(task, context.taskGraph);
};
export default buildHasher;
样板默认委托给 context.hasher.hashTask,行为与 Nx 默认 Hasher 完全一致;你只需在此函数内注入自定义输入(如读取环境变量、文件指纹等),即可扩展 Hash 计算逻辑。配套的 hasher.spec.ts.template 用 mock 的 TaskHasher 验证 Hasher 正确返回 Hash 值,可作为定制后的回归测试基准。
关于参数名称的说明
--includeHasher 中 “include” 一词的含义是:连同 Hasher 样板一起生成。注意区分 --includeHasher(本次生成时包含自定义 Hasher 文件)与 --skipLintChecks(跳过对插件 JSON 文件的 ESLint 配置)。若无需自定义缓存计算,保持默认的 includeHasher: false 即可,Nx 会为该 Executor 使用全局默认 Hasher。
生成器完整参数速查表
综合 schema.json 与类型定义 schema.d.ts,@nx/plugin:executor 支持以下参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
path |
string | 是 | — | Executor 文件路径(相对当前工作目录),支持带或不带 .ts 扩展名 |
name |
string | 否 | 由 path 推导 |
注册进插件 executors.json 的 Executor 名称 |
description |
string | 否 | ${name} executor |
Executor 描述,写入 executors.json |
unitTestRunner |
'jest' | 'vitest' | 'none' |
否 | jest |
单测框架;为 none 时删除 *.spec.ts 模板文件 |
includeHasher |
boolean | 否 | false |
是否同时生成自定义 Hasher 样板(hasher.ts) |
skipLintChecks |
boolean | 否 | false |
是否跳过对插件 JSON 文件的 ESLint 配置 |
skipFormat |
boolean | 否 | false |
生成后是否跳过 formatFiles 格式化(内部优先级参数) |
其中 unitTestRunner 的选择直接影响产物:传 none 时,addFiles 与 addHasherFiles 会显式删除对应的 spec 文件(见 executor.ts)。
executors.json 的自动注册过程
updateExecutorJson 是生成器核心副作用逻辑(executor.ts):
- 若插件的
package.json尚未声明executors字段,则通过createExecutorsJson自动写入executors: "./executors.json"并创建空壳executors.json(executor.ts); - 在 TS 工程方案(
isTsSolutionSetup)下,还会把executors.json追加到package.json的files发布白名单,确保发布 npm 包时包含注册文件; - 自动注入
"@nx/devkit": <nxVersion>到package.json的dependencies,保证运行时依赖可用; - 最后把
{ implementation, schema, description }(及可选hasher)写入executors.json的executors对象。
生成器兼容旧版 builders 字段:注册时优先读取 packageJson.executors ?? packageJson.builders,写入时也合并 json.executors ?? json.builders,保证新旧插件工程迁移无痛。
验证生成结果
生成完成后,可通过以下方式验证:
# 查看插件注册的 executors 列表
nx show project <plugin-project-name>
# 直接运行新生成的 executor(若目标项目已声明对应 target)
nx run <target-project>:custom
# 运行生成器自带的单元测试
nx test <plugin-project-name>
仓库中的 executor.spec.ts 提供了四类验证用例:基础文件生成、带扩展名路径、相对 cwd 的路径解析,以及 includeHasher 时 hasher.ts 的生成。编写自定义 Executor 后,建议参照这些用例补充自己的测试,确保 Executor 与 Hasher 在 CI 中的行为稳定可回归。
总结
@nx/plugin:executor 生成器围绕一条命令提供了四种典型的文件生成模式:基础生成(build.ts)、路径推断(省略扩展名)、导出名定制(--name)与自定义 Hashing(--includeHasher)。在仓库源码层面,它由路径规范化、模板渲染与 executors.json 注册三段逻辑构成,自动化处理了 @nx/devkit 依赖注入、Schema 生成与旧版 builders 兼容等细节。掌握这些参数与底层行为,你就能快速、规范地为 Nx 插件产出可发布、可测试、可定制缓存行为的 Executor。