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

如何通过Angular Schematics打印基于schema的自定义CLI帮助信息?

自定义Angular Schematics CLI帮助信息的实现方案

Angular Schematics核心CLI本身没有直接提供基于schema.json生成格式化帮助的内置方法,但可以通过以下两种方式实现需求:

方法一:在原理图入口中直接处理--help参数

在你的原理图入口文件中,手动判断命令行是否传入--help参数,读取schema.json并生成格式化的帮助文本输出:

import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
import * as fs from 'fs';
import * as path from 'path';

export function myCustomSchematic(options: any): Rule {
  return (tree: Tree, context: SchematicContext) => {
    // 检测--help参数
    if (options.help) {
      // 读取当前原理图的schema文件
      const schemaPath = path.join(__dirname, './schema.json');
      const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf-8'));
      
      // 生成类似Yargs风格的帮助文本
      let helpContent = `Usage: schematics @my-schematic:my-rule [options]\n\nOptions:\n`;
      Object.entries(schema.properties).forEach(([key, prop]: any) => {
        // 标记必填参数
        const requiredTag = schema.required?.includes(key) ? '*' : '';
        helpContent += `  --${key}${requiredTag}: ${prop.description || '无描述信息'}\n`;
        // 显示默认值(如果存在)
        if (prop.default !== undefined) {
          helpContent += `    默认值: ${JSON.stringify(prop.default)}\n`;
        }
        // 显示参数类型(如果存在)
        if (prop.type) {
          helpContent += `    类型: ${prop.type}\n`;
        }
      });
      
      // 输出帮助信息
      context.logger.info(helpContent);
      return tree;
    }

    // 正常执行原理图逻辑
    // ...
    return tree;
  };
}

使用时执行schematics @my-schematic:my-rule --help,就能输出基于你schema.json的自定义帮助。

方法二:编写独立的辅助脚本

如果需要更灵活的格式控制,可以写一个独立的Node.js脚本,直接读取schema.json生成帮助文本,然后将脚本绑定到npm命令(比如在package.json中添加"help": "node ./scripts/generate-help.js"):

// generate-help.js
const fs = require('fs');
const path = require('path');

const schema = JSON.parse(fs.readFileSync(path.join(__dirname, '../src/my-schematic/schema.json'), 'utf-8'));

let helpText = `@my-schematic:my-rule 自定义帮助\n\n`;
helpText += `可用参数:\n`;
Object.entries(schema.properties).forEach(([key, prop]) => {
  const required = schema.required?.includes(key) ? '[必填]' : '';
  helpText += `  --${key} ${required}\n`;
  helpText += `    ${prop.description || '无描述'}\n`;
  if (prop.enum) {
    helpText += `    可选值: ${prop.enum.join(', ')}\n`;
  }
});

console.log(helpText);

注意事项

  • 确保schema.json中的description、default、required、type等字段完整准确,才能生成有用的帮助信息
  • 若要实现和Yargs完全一致的样式(比如参数分组、颜色高亮),可以引入chalk等工具库优化输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:35:19