nx-generate
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRun Nx Generator
使用Nx Generator
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 generators是在单体仓库(monorepo)中搭建项目、执行自动化代码迁移或自动化重复任务的强大工具。它们确保代码库的一致性,减少样板代码的编写工作。
当用户有以下需求时,可应用此技能:
- 创建新的项目,如库或应用
- 搭建功能模块或样板代码
- 运行工作区专属或自定义的generator
- 执行任何已有Nx generator支持的操作
Generator Discovery Flow
Generator 发现流程
Step 1: List Available Generators
步骤1:列出可用的Generators
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)@nx/js:library - Local workspace generators (defined in the repo's own plugins)
使用Nx CLI查看可用的generators:
- 查看某个插件的所有generators:
npx nx list @nx/react - 查看所有可用插件:
npx nx list
可用的generators包括:
- 插件generators(例如、
@nx/react:library)@nx/js:library - 本地工作区generators(在仓库自身的插件中定义)
Step 2: Match Generator to User Request
步骤2:匹配Generator与用户需求
Based on the user's request, identify which generator(s) could fulfill their needs. Consider:
- What artifact type they want to create (library, application, etc.)
- Which framework or technology stack is relevant
- Whether they mentioned specific generator names
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 and conventions.
It's possible that the user request is something that no Nx generator exists for whatsoever. In this case, you can stop using this skill and try to help the user another way. HOWEVER, the burden of proof for this is high. Before aborting, carefully consider each and every generator that's available. Look into details for any that could be related in any way before making this decision.
根据用户的需求,确定哪些generator可以满足其需求。需考虑:
- 用户想要创建的产物类型(库、应用等)
- 相关的框架或技术栈
- 用户是否提到了特定的generator名称
重要提示:当本地工作区generator和外部插件generator都能满足需求时,优先使用本地工作区generator。本地generator是针对特定仓库的模式和约定定制的。
可能存在用户的需求没有任何Nx generator可以满足的情况。此时可停止使用此技能,尝试其他方式帮助用户。但在此之前,必须仔细检查所有可用的generator,深入研究任何可能相关的generator后再做决定。
Pre-Execution Checklist
执行前检查清单
Before running any generator, complete these steps:
在运行任何generator之前,请完成以下步骤:
1. Fetch Generator Schema
1. 获取Generator Schema
Use the flag to understand all available options:
--helpbash
npx nx g @nx/react:library --helpPay attention to:
- Required options that must be provided
- Optional options that may be relevant to the user's request
- Default values that might need to be overridden
使用参数了解所有可用选项:
--helpbash
npx nx g @nx/react:library --help需注意:
- 必须提供的必填选项
- 与用户需求相关的可选选项
- 可能需要覆盖的默认值
2. Read Generator Source Code
2. 阅读Generator源代码
Understanding what the generator actually does helps you:
- Know what files will be created/modified
- Understand any side effects (updating configs, installing deps, etc.)
- Identify options that might not be obvious from the schema
To find generator source code:
- For plugin generators: Use to find the generators.json, then locate the source from there
node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));" - If that fails, read directly from
node_modules/<plugin>/generators.json - For local generators: They are typically in or a local plugin directory. You can search the repo for the generator name to find it.
tools/generators/
了解generator的实际工作原理有助于:
- 知道会创建/修改哪些文件
- 了解任何副作用(如更新配置、安装依赖等)
- 发现Schema中未明确说明的选项
查找generator源代码的方法:
- 对于插件generators:使用找到generators.json文件,然后从中定位源代码
node -e "console.log(require.resolve('@nx/<plugin>/generators.json'));" - 如果上述方法失败,直接从读取
node_modules/<plugin>/generators.json - 对于本地generators:通常位于或本地插件目录中。可在仓库中搜索generator名称来找到它。
tools/generators/
2.5 Reevaluate if the generator is right
2.5 重新评估generator是否合适
Once you have built up an understanding of what the selected generator does, reconsider: Is this the right generator to service the user request?
If not, it's okay to go back to the Generator Discovery Flow and select a different generator before proceeding. If you do, make sure to go through the entire pre-execution checklist once more.
在充分了解所选generator的功能后,请再次确认:这是否是满足用户需求的正确generator?
如果不是,可以回到Generator发现流程,重新选择其他generator,并再次完成整个执行前检查清单。
3. Understand Repo Context
3. 了解仓库上下文
Before generating, examine the target area of the codebase:
- Look at similar existing artifacts (other libraries, applications, etc.)
- Identify patterns and conventions used in the repo
- Note naming conventions, file structures, and configuration patterns
- Try to match these patterns when configuring the generator
For example, if similar libraries are using a specific test runner, build tool or linter, try to match that if possible.
If projects or other artifacts are organized with a specific naming convention, try to match it.
在生成代码之前,请检查代码库的目标区域:
- 查看类似的现有产物(其他库、应用等)
- 识别仓库中使用的模式和约定
- 注意命名规范、文件结构和配置模式
- 配置generator时尽量匹配这些模式
例如,如果类似的库使用特定的测试运行器、构建工具或代码检查工具,请尽量保持一致。
如果项目或其他产物遵循特定的命名约定,请尽量匹配。
4. Validate Required Options
4. 验证必填选项
Ensure all required options have values:
- Map the user's request to generator options
- Infer values from context where possible
- Ask the user for any critical missing information
确保所有必填选项都有值:
- 将用户的需求映射到generator选项
- 尽可能从上下文中推断值
- 向用户询问无法推断的关键信息
Execution
执行阶段
Keep in mind that you might have to prefix things with npx/pnpx/yarn if the user doesn't have nx installed globally.
Many generators will behave differently based on where they are executed. For example, first-party nx library generators use the cwd to determine the directory that the library should be placed in. This is highly important.
请记住,如果用户没有全局安装nx,可能需要在命令前添加npx/pnpx/yarn前缀。
许多generator的行为会根据执行位置而有所不同。例如,官方的nx库generator会使用当前工作目录(cwd)来确定库的放置目录,这一点非常重要。
Consider Dry-Run (Optional)
考虑执行预运行(可选)
Running with first is strongly encouraged but not mandatory. Use your judgment:
--dry-run- For complex generators or unfamiliar territory: do a dry-run first
- For simple, well-understood generators: may proceed directly
- Dry-run shows file names and created/deleted/modified markers, but not content
- There are cases where a generator does not support dry-run (for example if it had to install an npm package) - in that case --dry-run might fail. Don't be discouraged but simply move on to running the generator for real and iterating from there.
强烈建议先使用参数进行预运行,但这不是强制性的。请根据实际情况判断:
--dry-run- 对于复杂的generator或不熟悉的场景:先执行预运行
- 对于简单、熟悉的generator:可直接执行
- 预运行会显示文件名和创建/删除/修改标记,但不会显示内容
- 有些generator不支持预运行(例如需要安装npm包的generator),此时可能会执行失败。无需气馁,直接执行实际生成操作并逐步调整即可。
--dry-run
Running the Generator
运行Generator
Execute the generator with:
bash
nx generate <generator-name> <options> --no-interactiveCRITICAL: Always include to prevent prompts that would hang the execution.
--no-interactiveExample:
bash
nx generate @nx/react:library --name=my-utils --no-interactive使用以下命令执行generator:
bash
nx generate <generator-name> <options> --no-interactive关键提示:务必添加参数,以避免出现导致执行挂起的交互式提示。
--no-interactive示例:
bash
nx generate @nx/react:library --name=my-utils --no-interactiveHandling Generator Failures
处理Generator执行失败
If the generator fails:
- Diagnose the error - Read the error message carefully
- Identify the cause - Missing options, invalid values, conflicts, etc.
- Attempt automatic fix - Adjust options or resolve conflicts
- Retry - Run the generator again with corrected options
Common failure reasons:
- Missing required options
- Invalid option values
- Conflicting with existing files
- Missing dependencies
- Generator doesn't support certain flag combinations
如果generator执行失败:
- 诊断错误 - 仔细阅读错误信息
- 确定原因 - 缺少选项、值无效、冲突等
- 尝试自动修复 - 调整选项或解决冲突
- 重试 - 使用修正后的选项重新运行generator
常见失败原因:
- 缺少必填选项
- 选项值无效
- 与现有文件冲突
- 缺少依赖
- Generator不支持某些标志组合
Post-Generation
生成后操作
1. Modify Generated Code (If Needed)
1. 修改生成的代码(如有需要)
Generators provide a starting point, but the output may need adjustment to match the user's specific requirements:
- Add or modify functionality as requested
- Adjust imports, exports, or configurations
- Integrate with existing code patterns in the repo
Generator提供的是起点,输出结果可能需要调整以匹配用户的具体需求:
- 根据需求添加或修改功能
- 调整导入、导出或配置
- 与仓库中现有的代码模式集成
2. Format Code
2. 格式化代码
Run formatting on all generated/modified files:
bash
nx format --fixLanguages other than javascript/typescript might need other formatting invocations too.
对所有生成/修改的文件执行格式化:
bash
nx format --fixJavaScript/TypeScript以外的语言可能需要其他格式化命令。
3. Run Verification
3. 执行验证
Verify that the generated code works correctly. What this looks like will vary depending on the type of generator and the targets available.
If the generator created a new project, run its targets directly
Use your best judgement to determine what needs to be verified.
Example:
bash
nx lint <new-project>
nx test <new-project>
nx build <new-project>验证生成的代码是否能正常工作。具体的验证方式会根据generator的类型和可用的目标任务而有所不同。
如果generator创建了新项目,直接运行其目标任务
请根据实际情况判断需要执行哪些验证操作。
示例:
bash
nx lint <new-project>
nx test <new-project>
nx build <new-project>4. Handle Verification Failures
4. 处理验证失败
When verification fails:
If scope is manageable (a few lint errors, minor type issues):
- Fix the issues
- Re-run verification to confirm
If issues are extensive (many errors, complex problems):
- Attempt simple, obvious fixes first
- If still failing, escalate to the user with:
- Description of what was generated
- What verification is failing
- What you've attempted to fix
- Remaining issues that need user input
当验证失败时:
如果问题范围可控(少量代码检查错误、轻微类型问题):
- 修复问题
- 重新执行验证以确认修复成功
如果问题范围较大(大量错误、复杂问题):
- 先尝试简单、明显的修复
- 如果仍然失败,向用户反馈以下信息:
- 生成的内容描述
- 验证失败的具体内容
- 已尝试的修复操作
- 需要用户输入的剩余问题
Error Handling
错误处理
Generator Failures
Generator执行失败
- Check the error message for specific causes
- Verify all required options are provided
- Check for conflicts with existing files
- Ensure the generator name and options are correct
- 检查错误信息以确定具体原因
- 验证所有必填选项是否已提供
- 检查是否与现有文件冲突
- 确保generator名称和选项正确
Missing Options
缺少选项
- Consult the generator schema for required fields
- Infer values from context when reasonable
- Ask the user for values that cannot be inferred
- 查阅generator schema获取必填字段
- 合理地从上下文中推断值
- 向用户询问无法推断的值
Key Principles
核心原则
-
Local generators first - Always prefer workspace/local generators over external plugin generators when both could work
-
Understand before running - Read both the schema AND the source code to fully understand what will happen
-
No prompts - Always useto prevent hanging
--no-interactive -
Generators are starting points - Modify the output as needed to fully satisfy the user's requirements
-
Verify changes work - Don't just generate; ensure the code builds, lints, and tests pass
-
Be proactive about fixes - Don't just report errors; attempt to resolve them automatically when possible
-
Match repo patterns - Study existing similar code in the repo and match its conventions
-
优先使用本地generator - 当本地工作区generator和外部插件generator都能满足需求时,始终优先选择本地generator
-
先理解再运行 - 同时阅读schema和源代码,以充分了解执行后会发生的操作
-
无交互式提示 - 始终使用参数,避免执行挂起
--no-interactive -
Generator仅为起点 - 根据需要修改输出结果,以完全满足用户的需求
-
验证修改是否可用 - 不要只生成代码,还要确保代码能构建、通过代码检查和测试
-
主动修复问题 - 不要只报告错误,尽可能尝试自动解决问题
-
匹配仓库模式 - 研究仓库中现有的类似代码,匹配其约定