【问题标题】:ClassOptions Schema - Angular SchematicsClassOptions Schema - Angular Schematics
【发布时间】:2019-06-21 16:41:59
【问题描述】:

在 @angular-devkit/schematics readme 中,我对 ClassOptions 的作用感到困惑。

如果将代码添加到项目中,则会显示错误,因为该文件不存在。

想知道这是做什么用的 + 一个例子?

import { strings } from '@angular-devkit/core';
import {
  Rule, SchematicContext, SchematicsException, Tree,
  apply, branchAndMerge, mergeWith, template, url,
} from '@angular-devkit/schematics';
import { Schema as ClassOptions } from './schema';

export default function (options: ClassOptions): Rule {
  return (tree: Tree, context: SchematicContext) => {
    if (!options.name) {
      throw new SchematicsException('Option (name) is required.');
    }

    const templateSource = apply(
      url('./files'),
      [
        template({
          ...strings,
          ...options,
        }),
      ]
    );

    return branchAndMerge(mergeWith(templateSource));
  };
} 

【问题讨论】:

    标签: angular angular-cli angular-schematics angular-devkit


    【解决方案1】:

    示例中的schema 文件是在build processangular-cli 中使用this function 生成的打字稿文件。这是angular-cli 中使用的模式,该示例无法正常工作。您可以在service 等官方角度示意图之一中查看此类示意图的完整示例。

    但请记住,ClassOptions 只是一个指定 Angular Schematic 选项的对象。它可以来自任何地方,并且与原理图库分离。 responsibility of the tooling 为原理图库提供选项。

    这是一个使用reference cli 的类似示例。

    生成一个简单的示意图:

    schematics blank --name=test
    

    将架构文件的路径添加到collection.json

    {
      "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
      "schematics": {
        "test": {
          "description": "A blank schematic.",
          "factory": "./test/index#test",
          "schema": "./test/schema.json"
        }
      }
    }
    

    创建schema.json:

    {
        "$schema": "http://json-schema.org/schema",
        "id": "MySchema",
        "title": "My Schema",
        "type": "object",
        "properties": {
            "name": {
                "type": "string",
                "default": "cactus"
            }
        }
    }
    

    index.ts 中的工厂现在将从schema.json 文件中传递默认选项。

    import { Rule, SchematicContext, Tree } from "@angular-devkit/schematics";
    
    // You don't have to export the function as default. You can also have more than one rule factory
    // per file.
    export function test(_options: any): Rule {
        return (tree: Tree, _context: SchematicContext) => {
            tree.create(_options.name || "hello", "world");
            return tree;
        };
    }
    

    使用 schema.json 的默认值运行 cli:

    schematics .:test --dry-run=false
    ...
    CREATE /cactus (5 bytes)
    

    使用用户定义的选项运行 cli:

    schematics .:test --name=bean--dry-run=false
    ...
    CREATE /bean (5 bytes)
    

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2021-11-16
      • 1970-01-01
      • 2019-09-08
      • 2018-10-23
      • 2021-05-12
      • 2018-11-02
      • 2021-06-17
      • 2020-04-05
      相关资源
      最近更新 更多