【问题标题】:Angular schematics: apply rules to the current tree and then modify the tree角度示意图:将规则应用于当前树,然后修改树
【发布时间】:2020-04-24 23:58:31
【问题描述】:

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

正如下面sn-p中解释的,我想应用创建的规则,所以tree.exists("./file.txt")返回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') 仍然返回 false。

【问题讨论】:

  • 问题是什么?
  • 读取代码里面的cmets

标签: angular angular-schematics


【解决方案1】:

编辑

只需调用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;
    }
}

并且总是尝试提供一些合并策略。

【讨论】:

  • 不起作用,虽然返回了创建文件的规则,即:return chain(...),但是这种方法在返回后没有机会完成代码。还有 `chain([branchAndMerge(chain([mergeWith(tmpl)]))]);` 没用。
  • 也许将 if-create 部分拆分到另一个函数中,返回规则并与前一个链接可以工作。
  • 你自己测试过吗?如果你这样做了,请给我测试过的代码。
  • 检查编辑的答案。我没有对其进行测试,但这就是我在大多数原理图上所做的。
猜你喜欢
  • 2018-12-26
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 2016-07-14
  • 2015-06-27
  • 1970-01-01
相关资源
最近更新 更多