如何从自定义 Angular 原理图访问 Angular 项目文件夹?

How to access Angular project folder from a custom Angular schematic?

我正在开发自定义 Angular 原理图。该原理图必须访问 Angular 项目内的一个文件夹,该文件夹将使用该原理图。 (该文件夹包含生成我的 .ts 文件所需的配置文件)。原理图将提示用户输入路径(存储在 configFilesPath 中)

到目前为止,我只能通过这种方式访问​​此文件夹:

export const readConfigFilefromPath = (configFilesPath: string): string | undefined => {

  // ...

  const path = __dirname + "\..\..\..\..\..\src\app\" + configFilesPath;

  // ...
}

有没有更好的方法从原理图访问路径?

有趣的是,您试图在原理图中读取外部配置文件,通常人们会尝试通过选项传递所有配置。

也就是说,这是一种方法 - 在您的示意图中读入 angular.json 并提取您关心的项目的 sourceRoot 属性:

import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { experimental } from '@angular-devkit/core';

function getSourceRoot(sProjectName: string, cTree: Tree) {

    const sWorkspaceConfig = cTree.read('/angular.json');

    if (!sWorkspaceConfig) {
        throw new SchematicsException('Could not find Angular workspace configuration');
    }

    const cWorkspace: experimental.workspace.WorkspaceSchema = JSON.parse(sWorkspaceConfig.toString());

    return cWorkspace.projects[sProjectName].sourceRoot;

}

获得源根目录后,您可以将相对路径附加到配置文件。如果你想避免这种事情,我唯一能想到的就是为每个配置文件创建一个示意图,然后将配置硬编码到示意图中(可能不适合你的情况)。