0

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

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

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

  // ...

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

  // ...
}

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

4

1 回答 1

0

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

话虽如此,这是一种方法 - 在原理图中读取 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;

}

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

于 2020-05-06T12:55:24.773 回答