4

在 @angular-devkit/schematics自述文件中,我对 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));
  };
} 
4

1 回答 1

1

示例中的文件是在构建过程中使用此函数schema生成的打字稿文件。这是一种使用的模式,示例无法按原样工作。您可以在官方的角度示意图之一(如service)中查看此类示意图的完整示例。angular-cliangular-cli

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

这是使用参考 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;
    };
}

使用以下默认值运行 cli schema.json

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

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

schematics .:test --name=bean--dry-run=false
...
CREATE /bean (5 bytes)
于 2019-01-31T16:59:43.837 回答