如何在自定义 Angular 示意图中定位文件路径?

How to target filepath in custom Angular Schematics?

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

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' 创建了一个文件。我将如何更改树的文件路径,以便将文件输出到各种自定义目录中?谢谢你。

你可以这样做

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);
    }
}

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

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;
  };
}