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

如何在自定义NX Generator中条件生成指定模板文件?

实现NX生成器条件生成文件的方案

方案一:用@nx/devkit的generateFiles直接实现

完全可以通过generateFiles实现条件生成,核心就是在调用方法前加条件判断:

  • 先在生成器逻辑里定义你的特定判断条件(比如用户输入的参数、项目配置字段等)
  • 当条件为真时,才执行generateFiles生成目标文件

示例代码:

import { generateFiles, Tree } from '@nx/devkit';
import { join } from 'path';

export default async function (tree: Tree, schema: any) {
  // 替换为你的实际判断条件
  const shouldGenerateConditionalFile = schema.includeConditionalFile;

  if (shouldGenerateConditionalFile) {
    generateFiles(
      tree,
      // 模板文件所在路径
      join(__dirname, './files'),
      // 目标项目路径
      schema.projectRoot,
      // 模板变量(无则传空对象)
      { ...schema, tmpl: '' }
    );
  }

  // 原有逻辑:调用@nx/express生成器等
}

如果.ts是单独的模板,可以单独指定该模板的路径,不用和其他模板放在一起,灵活性更高。

方案二:用writeIfNotExists手动生成(适合简单文件)

如果目标文件内容简单,不需要模板渲染,也可以用@nx/devkit的writeIfNotExists配合条件判断:

import { writeIfNotExists, Tree } from '@nx/devkit';

export default async function (tree: Tree, schema: any) {
  const shouldGenerateConditionalFile = schema.includeConditionalFile;

  if (shouldGenerateConditionalFile) {
    const filePath = `${schema.projectRoot}/src/<conditional file>.ts`;
    const fileContent = `// 自定义文件内容
export const customConfig = { key: 'value' };
`;
    writeIfNotExists(tree, filePath, fileContent);
  }
}

方案三:模板加标记后批量生成再删除(适合多模板场景)

如果模板目录里有多个文件,仅单个文件需要条件生成,可以给模板加特殊标记,生成后根据条件删除不需要的文件:

  1. 在.ts.tmpl开头加注释标记:// CONDITIONAL_FILE
  2. 先调用generateFiles生成所有模板,再判断条件删除目标文件:
import { generateFiles, Tree, deleteFile } from '@nx/devkit';
import { join } from 'path';

export default async function (tree: Tree, schema: any) {
  const shouldGenerateConditionalFile = schema.includeConditionalFile;

  // 生成所有模板文件
  generateFiles(
    tree,
    join(__dirname, './files'),
    schema.projectRoot,
    { ...schema, tmpl: '' }
  );

  // 条件不满足则删除目标文件
  if (!shouldGenerateConditionalFile) {
    const conditionalFilePath = `${schema.projectRoot}/src/<conditional file>.ts`;
    if (tree.exists(conditionalFilePath)) {
      deleteFile(tree, conditionalFilePath);
    }
  }
}

三种方案里,方案一最直接高效,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:38:15