nx-generate

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Run Nx Generator

运行Nx生成器

Nx generators are powerful tools that scaffold projects, make automated code migrations or automate repetitive tasks in a monorepo. They ensure consistency across the codebase and reduce boilerplate work.
This skill applies when the user wants to:
  • Create new projects like libraries or applications
  • Scaffold features or boilerplate code
  • Run workspace-specific or custom generators
  • Do anything else that an nx generator exists for
Nx生成器是在单体仓库(monorepo)中搭建项目、执行自动化代码迁移或完成重复性任务的强大工具。它们确保代码库的一致性,减少样板代码的编写工作。
当用户有以下需求时,可应用此技能:
  • 创建新的项目,如库或应用程序
  • 搭建功能模块或样板代码
  • 运行工作区专属或自定义生成器
  • 任何Nx生成器支持的操作

Key Principles

核心原则

  1. Always use
    --no-interactive
    - Prevents prompts that would hang execution
  2. Read the generator source code - The schema alone is not enough; understand what the generator actually does
  3. Match existing repo patterns - Study similar artifacts in the repo and follow their conventions
  4. Verify with lint/test/build - Generated code must pass verification
  1. 始终使用
    --no-interactive
    参数
    - 避免出现会导致执行停滞的交互提示
  2. 阅读生成器源代码 - 仅靠配置模式(schema)不足以了解全部,需明确生成器的实际功能
  3. 匹配现有仓库的模式 - 研究仓库中类似的项目产物,遵循其约定规范
  4. 通过lint/test/build验证 - 生成的代码必须能通过验证

Steps

操作步骤

1. Discover Available Generators

1. 发现可用的生成器

Use the Nx CLI to discover available generators:
  • List all generators for a plugin:
    npx nx list @nx/react
  • View available plugins:
    npx nx list
This includes plugin generators (e.g.,
@nx/react:library
) and local workspace generators.
使用Nx CLI查看可用的生成器:
  • 列出某个插件的所有生成器:
    npx nx list @nx/react
  • 查看所有可用插件:
    npx nx list
其中包括插件生成器(例如
@nx/react:library
)和本地工作区生成器。

2. Match Generator to User Request

2. 匹配生成器与用户需求

Identify which generator(s) could fulfill the user's needs. Consider what artifact type they want, which framework is relevant, and any specific generator names mentioned.
IMPORTANT: When both a local workspace generator and an external plugin generator could satisfy the request, always prefer the local workspace generator. Local generators are customized for the specific repo's patterns.
If no suitable generator exists, you can stop using this skill. However, the burden of proof is high—carefully consider all available generators before deciding none apply.
确定哪些生成器可以满足用户需求。考虑用户需要的产物类型、相关框架以及提到的特定生成器名称。
重要提示:当本地工作区生成器和外部插件生成器都能满足需求时,优先使用本地工作区生成器。本地生成器是针对当前仓库的模式定制的。
如果没有合适的生成器,可以停止使用此技能。但需谨慎判断——在确定没有可用生成器之前,请仔细排查所有选项。

3. Get Generator Options

3. 获取生成器选项

Use the
--help
flag to understand available options:
bash
npx nx g @nx/react:library --help
Pay attention to required options, defaults that might need overriding, and options relevant to the user's request.
使用
--help
参数了解可用选项:
bash
npx nx g @nx/react:library --help
重点关注必填选项、可能需要覆盖的默认值,以及与用户需求相关的选项。

Library Buildability

库的可构建性

Default to non-buildable libraries unless there's a specific reason for buildable.
TypeWhen to useGenerator flags
Non-buildable (default)Internal monorepo libs consumed by appsNo
--bundler
flag
BuildablePublishing to npm, cross-repo sharing, stable libs for cache hits
--bundler=vite
or
--bundler=swc
Non-buildable libs:
  • Export
    .ts
    /
    .tsx
    source directly
  • Consumer's bundler compiles them
  • Faster dev experience, less config
Buildable libs:
  • Have their own build target
  • Useful for stable libs that rarely change (cache hits)
  • Required for npm publishing
If unclear, ask the user: "Should this library be buildable (own build step, better caching) or non-buildable (source consumed directly, simpler setup)?"
默认使用不可构建的库,除非有特定理由需要可构建库。
类型使用场景生成器参数
不可构建(默认)单体仓库内部供应用程序使用的库不添加
--bundler
参数
可构建发布到npm、跨仓库共享、用于缓存命中的稳定库
--bundler=vite
--bundler=swc
不可构建的库:
  • 直接导出
    .ts
    /
    .tsx
    源码
  • 由消费方的打包工具编译
  • 开发体验更快,配置更简单
可构建的库:
  • 拥有独立的构建目标
  • 适合很少变更的稳定库(可命中缓存)
  • 发布到npm时必须使用
如果不确定,请询问用户:“此库应该设置为可构建(拥有独立构建步骤,缓存效果更好)还是不可构建(直接提供源码,设置更简单)?”

4. Read Generator Source Code

4. 阅读生成器源代码

This step is critical. The schema alone does not tell you everything. Reading the source code helps you:
  • Know exactly what files will be created/modified and where
  • Understand side effects (updating configs, installing deps, etc.)
  • Identify behaviors and options not obvious from the schema
  • Understand how options interact with each other
To find generator source code:
  • For plugin generators: Use
    node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"
    to find the generators.json, then locate the source from there
  • If that fails, read directly from
    node_modules/<plugin>/generators.json
  • For local generators: Typically in
    tools/generators/
    or a local plugin directory. Search the repo for the generator name.
After reading the source, reconsider: Is this the right generator? If not, go back to step 2.
⚠️
--directory
flag behavior can be misleading.
It should specify the full path of the generated library or component, not the parent path that it will be generated in.
bash
# ✅ Correct - directory is the full path for the library
nx g @nx/react:library --directory=libs/my-lib
# generates libs/my-lib/package.json and more

# ❌ Wrong - this will create files at libs and libs/src/...
nx g @nx/react:library --name=my-lib --directory=libs
# generates libs/package.json and more
此步骤至关重要。仅靠配置模式无法了解全部信息。阅读源代码有助于:
  • 明确会创建/修改哪些文件以及位置
  • 了解副作用(如更新配置、安装依赖等)
  • 发现配置模式中未体现的行为和选项
  • 理解选项之间的交互逻辑
查找生成器源代码的方法:
  • 对于插件生成器:使用
    node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));"
    找到generators.json文件,然后从中定位源代码
  • 如果上述方法失败,直接查看
    node_modules/<plugin>/generators.json
  • 对于本地生成器:通常位于
    tools/generators/
    或本地插件目录中。在仓库中搜索生成器名称即可找到。
阅读源代码后,请重新确认:这是否是正确的生成器?如果不是,返回步骤2重新选择。
⚠️
--directory
参数的行为容易混淆
它应指定生成的库或组件的完整路径,而非它将被生成到的父路径。
bash
# ✅ 正确用法 - directory是库的完整路径
nx g @nx/react:library --directory=libs/my-lib
# 生成文件到libs/my-lib/package.json及其他相关目录

# ❌ 错误用法 - 会在libs和libs/src/...创建文件
nx g @nx/react:library --name=my-lib --directory=libs
# 生成文件到libs/package.json及其他相关目录

5. Examine Existing Patterns

5. 参考现有模式

Before generating, examine the target area of the codebase:
  • Look at similar existing artifacts (other libraries, applications, etc.)
  • Identify naming conventions, file structures, and configuration patterns
  • Note which test runners, build tools, and linters are used
  • Configure the generator to match these patterns
在生成代码之前,检查代码库的目标区域:
  • 查看类似的现有产物(其他库、应用程序等)
  • 确定命名规范、文件结构和配置模式
  • 记录使用的测试运行器、构建工具和代码检查工具
  • 配置生成器以匹配这些模式

6. Dry-Run to Verify File Placement

6. 试运行以验证文件位置

Always run with
--dry-run
first
to verify files will be created in the correct location:
bash
npx nx g @nx/react:library --name=my-lib --dry-run --no-interactive
Review the output carefully. If files would be created in the wrong location, adjust your options based on what you learned from the generator source code.
Note: Some generators don't support dry-run (e.g., if they install npm packages). If dry-run fails for this reason, proceed to running the generator for real.
请始终先使用
--dry-run
参数试运行
,以验证文件是否会被创建在正确的位置:
bash
npx nx g @nx/react:library --name=my-lib --dry-run --no-interactive
仔细检查输出结果。如果文件会被创建在错误的位置,请根据从生成器源代码中学到的知识调整参数。
注意:部分生成器不支持试运行(例如需要安装npm包的生成器)。如果因此导致试运行失败,可以直接执行生成器。

7. Run the Generator

7. 运行生成器

Execute the generator:
bash
nx generate <generator-name> <options> --no-interactive
Tip: New packages often need workspace dependencies wired up (e.g., importing shared types, being consumed by apps). The
link-workspace-packages
skill can help add these correctly.
执行生成器:
bash
nx generate <generator-name> <options> --no-interactive
提示:新的包通常需要关联工作区依赖(例如导入共享类型、被应用程序引用)。
link-workspace-packages
技能可以帮助正确完成这些配置。

8. Modify Generated Code (If Needed)

8. 修改生成的代码(如有需要)

Generators provide a starting point. Modify the output as needed to:
  • Add or modify functionality as requested
  • Adjust imports, exports, or configurations
  • Integrate with existing code patterns
Important: If you replace or delete generated test files (e.g.,
*.spec.ts
), either write meaningful replacement tests or remove the
test
target from the project configuration. Empty test suites will cause
nx test
to fail.
生成器提供的是基础代码。可根据需要修改输出内容:
  • 根据需求添加或修改功能
  • 调整导入、导出或配置
  • 与现有代码模式集成
重要提示:如果替换或删除生成的测试文件(例如
*.spec.ts
),请编写有意义的替代测试,或者从项目配置中移除
test
目标。空的测试套件会导致
nx test
执行失败。

9. Format and Verify

9. 格式化与验证

Format all generated/modified files:
bash
nx format --fix
Then verify the generated code works:
bash
nx lint <new-project>
nx test <new-project>
nx build <new-project>
If verification fails with manageable issues (a few lint errors, minor type issues), fix them. If issues are extensive, attempt obvious fixes first, then escalate to the user with details about what was generated, what's failing, and what you've attempted.
格式化所有生成/修改的文件:
bash
nx format --fix
然后验证生成的代码是否可用:
bash
nx lint <new-project>
nx test <new-project>
nx build <new-project>
如果验证失败且问题可处理(例如少量代码检查错误、轻微类型问题),请修复这些问题。如果问题较多,请先尝试明显的修复,然后向用户详细说明生成的内容、失败的原因以及已尝试的修复措施。