Angular schematics: 将规则应用于当前树,然后修改树

Angular schematics: apply rules to the current tree and then modify the tree

我正在创建一个 Angular 示意图。 我想对当前树应用一个规则,然后修改树。

如以下代码段所述,我想应用创建的规则,所以 tree.exists("./file.txt") returns true

export default function(options: any): Rule {
  return (tree: Tree, context: SchematicContext) => {
    let tmpl = apply(url("./files"), [template(options),move(".")]);
    let rule = chain([branchAndMerge(chain([mergeWith(tmpl)]))]);
     //how to apply this rule to the current tree, so it contains the files from ./files

    //assume ./files contain a file named myfile.txt
    console.log(tree.exists("./myfile.txt"))    


    tree.create("hello.txt", "");
    return tree;
  };
}

笔记

return rule; 创建 /file.txt,但我想通过 tree.create() 函数创建文件 file.txt(通过应用规则)和 hello.txt .

在应用规则之前使用 tree.create() 创建两个文件,但 tree.exists('./file.txt') 仍然 returns false。

编辑

只调用chain而不分配变量:

export default function(options: any): Rule {
    return (tree: Tree) => {
        const templateSource = apply(
            url("./files"),
            [template(options), move(".")]
        );

        const rules: Rule[] = [];
        rules.push(mergeWith(templateSource, MergeStrategy.Overwrite));
        rules.push(createFiles());
        return chain(rules);
    };
}

function createFiles(): Rule {
    return (tree: Tree) => {
        // Check if ./files contain a file named myfile.txt
        if (tree.exists("./myfile.txt")) {
            // Do whatever you want.
        }

        // You should check if it exists. If it does, use ovewrite instead.
        tree.create("hello.txt", "");
        return tree;
    }
}

并且始终尝试提供一些合并策略。