【问题标题】:How to target filepath in custom Angular Schematics?如何在自定义 Angular Schematics 中定位文件路径?
【发布时间】:2018-12-15 11:14:04
【问题描述】:

我目前正在尝试创建自己的自定义 Angular Schematics。我有以下内容:

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 pxSchematics(options: any): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    tree.create(options.name || 'hello', 'world');
    return tree;
  };
}

这只是创建一个带有“hello world”的文件。我将如何更改树的文件路径,以便将文件输出到各种自定义目录中?谢谢你。

【问题讨论】:

    标签: angular angular-cli angular-schematics


    【解决方案1】:

    您可以只指定所需的路径:

    import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
    import { normalize } from "@angular-devkit/core";
    
    export function pxSchematics(options: any): Rule {
      return (tree: Tree, _context: SchematicContext) => {
        tree.create(options.name || normalize('sorts/hello'), 'world');
        return tree;
      };
    }
    

    【讨论】:

    • options.name 路由可以在原理图项目之外,在上层文件夹中吗?
    • @RicardoDaniel 我认为树的顶部是您执行命令的地方。您可以使用 nodejs 方法 ..
    • 实际上是的.... options.name 在原理图项目之外,这就是我认为的问题。你说我可以使用例如 Node.js 文件系统模块吗?
    • 我尝试使用基本 node.js 代码创建一个文件,并且它可以工作。显然顶部是原理图项目目录。相反我会重构,用node.js读取文件,只使用原理图的上限写入(可能是出于安全原因)
    • 是的...实际上,经过大量工作后,我决定使用挂钩后安装,原理图非常适合模板化,处理项目结构,但如果您在 angular.json 上更改一些路线为了使您的应用程序扩展,在主目录之外处理这些情况非常困难
    【解决方案2】:

    你可以这样做

    import {chain, move, Rule, SchematicContext, Tree} from "@angular-devkit/schematics";
    import {Schema as ApplicationOptions} from "@schematics/angular/application/schema";
    
    export default function (options: ApplicationOptions): Rule {
        return (tree: Tree, _context: SchematicContext) => {
            console.log(_context);
            const result = (tree: Tree, _context: SchematicContext) => {
                tree.create(options.name || 'hello', 'world')
                return tree;
            }
            // Here you can get whatever from options
            const desiredPath = 'src';
            return chain([
                    result,
                    move(options.name || 'hello', `${desiredPath}/${options.name || 'hello'}`)
                ]
            )(tree, _context);
        }
    }
    

    【讨论】:

    • 是的,我试过了......但它一直说:错误:路径“/../../src/hello”无效。
    猜你喜欢
    • 2017-06-19
    • 2021-02-02
    • 2021-05-12
    • 2019-09-05
    • 1970-01-01
    • 2023-04-09
    • 2023-04-01
    • 2012-04-21
    • 1970-01-01
    相关资源
    最近更新 更多