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

如何让Angular Schematics继承自定义基础Schematic的Schema与规则?

Angular Schematics 实现私有Base Schematic的Schema与Rules继承方案

Angular Schematics本身没有提供直接让一个schematic完全扩展另一个的内置一键机制,但可以通过以下更简洁的方式实现需求,无需完全依赖自定义类继承:

1. Schema 合并复用

利用JSON Schema的$ref和allOf关键字,直接复用私有Base的Schema结构,同时合并foo自身的字段:

// foo/schema.json
{
  "$schema": "http://json-schema.org/schema",
  "allOf": [
    { "$ref": "../base/base-schema.json" }, // 引入私有Base的Schema文件
    {
      "properties": {
        "fooSpecificProp": {
          "type": "string",
          "description": "Foo schematic专属配置项"
        }
      }
    }
  ],
  "required": [] // 可合并Base的必填项,或新增foo自己的必填项
}

2. Rules 继承执行

在foo的schematic工厂函数中,直接导入Base的规则生成逻辑,将Base的规则数组与foo自定义规则合并执行:

// foo/index.ts
import { Rule, SchematicContext, Tree, chain } from '@angular-devkit/schematics';
import { getBaseRules } from '../base/base-rules'; // 导入Base的规则生成函数

export function foo(options: any): Rule {
  return (tree: Tree, context: SchematicContext) => {
    // 先执行Base规则,再执行foo自定义规则(顺序可按需调整)
    return chain([
      ...getBaseRules(options),
      // foo专属规则示例
      (tree: Tree) => {
        tree.create('foo-custom-file.txt', 'Generated by foo schematic');
        return tree;
      }
    ])(tree, context);
  };
}

如果Base的规则是通过工厂函数生成的,直接传入foo的配置参数即可实现参数复用。

3. 确保Base Schematic私有不可调用

在项目的collection.json中只注册foo schematic,不添加Base的条目,这样CLI无法识别Base schematic,自然无法通过命令行调用:

// collection.json
{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "foo": {
      "description": "继承私有Base的Foo schematic",
      "factory": "./foo/index#foo",
      "schema": "./foo/schema.json"
    }
    // 不注册Base的schematic条目
  }
}

关于collection.json的extends字段

你提到的extends字段核心作用是覆盖已有collection中的schematic(比如扩展官方Angular schematics),逻辑是替换而非合并,确实不适合这种私有schematic的继承场景。

内容的提问来源于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:20