如何用角度示意图覆盖文件? [英] How to overwrite file with angular schematics?

查看:116
本文介绍了如何用角度示意图覆盖文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个Rule每次都覆盖一个文件.在以下内容中,将MergeStrategy设置为Overwrite:

I want to write a Rule that overwrites a file every time. In the following and have MergeStrategy set to Overwrite:

collection.json

{
  "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
  "schematics": {
    "function": {
      "aliases": [ "fn" ],
      "factory": "./function",
      "description": "Create a function.",
      "schema": "./function/schema.json"
    }
  }
}

function/index.ts

export default function(options: FunctionOptions): Rule {
  options.path = options.path ? normalize(options.path) : options.path;
  const sourceDir = options.sourceDir;
  if (!sourceDir) {
    throw new SchematicsException(`sourceDir option is required.`);
  }

  const templateSource: Source = apply(
    url('./files'),
    [
      template({
        ...strings,
        ...options,
      }),
      move(sourceDir),
    ]
  )

  return mergeWith(templateSource, MergeStrategy.Overwrite);

}

files/__path__/__name@dasherize__.ts

export function <%= camelize(name) %>(): void {
}

我运行schematics .:function --name=test --dry-run=false我得到

创建/src/app/test.ts(33字节)

CREATE /src/app/test.ts (33 bytes)

但是第二次.

错误!/src/app/test.ts已经存在.

ERROR! /src/app/test.ts already exists.

是否应该在没有错误的情况下覆盖文件test.ts?

Should it not overwrite the file test.ts with out error?

所有答案均有效,并且效果很好,但似乎它们是解决方法,没有明显的正确"答案,并且可能基于偏爱/自以为是.因此,不确定如何标记为已回答.

All of the answers work and are great but it seems they are workarounds and no obvious "right" answer and possibly based on preference / opinionated. So not sure how to mark as answered.

推荐答案

我遇到了同样的问题.偶然地,我发现在apply中添加forEach允许删除文件并创建新文件.这是@ angular-devkit/schematics-cli @ 0.6.8.

I experienced the same issue. By accident I found that adding a forEach into the apply allowed the files to be deleted and the new files created. This is with @angular-devkit/schematics-cli@0.6.8.

export function indexPage(options: any): Rule {
    return (tree: Tree, _context: SchematicContext) => {
        const rule = mergeWith(
            apply(url('./files'), [
                template({ ...options }),
                forEach((fileEntry: FileEntry) => {
                    // Just by adding this is allows the file to be overwritten if it already exists
                    if (tree.exists(fileEntry.path)) return null;
                    return fileEntry;
                })

            ])
        );

        return rule(tree, _context);
    };
}

这篇关于如何用角度示意图覆盖文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆