如何在Angular原理图中使用当前路径

时间:2019-09-02 07:27:58

标签: angular angular-schematics

我正在开发一个产生一些文件的原理图。我想在当前目录中拥有新文件,即

我的项目根目录为/src/app。当我在文件夹/src/app/features/f1中时,键入

ng g my:some-schemaitc --name=name

我希望有新文件

/src/app/features/f1/name.ts

相反,结果是

/src/app/name.ts

我想实现与ng g class --name=name相同的行为。当我在目录ng g class --name=class中键入/src/app/features/f1时,结果将是

/src/app/features/f1/class.ts

我试图模仿Angular ng g class的行为schematics source code,但没有令人满意的结果。我的代码几乎一样。

有人使用了当前路径吗?

2 个答案:

答案 0 :(得分:1)

偶然地,我发现了一个存储当前路径的全局变量__dirname。例如:

console.log('DIR', __dirname);

答案 1 :(得分:0)

遵循angular docs

中提到的步骤

您会遇到一些问题。例如

1)constworkspaceConfig = tree.read('/ angular.json');

//在使用'schematics'命令时将为null,但在使用'ng g'逗号时将起作用。

2)同样,当使用“ schematics”命令时,“ options.path”将是未定义的,但在使用“ ng g”命令时,将可使用。

您需要将路径添加到schema.json文件,然后在函数中,应该能够使用“ options.path”来获取当前位置。但是,正如我提到的那样,在使用“示意图”命令时我无法使其正常工作。我只能在使用'ng g'命令时使其工作。

例如,这是我的文件

1)..schematics / ng-generate / customComponent / schema.json

{
    "$schema": "http://json-schema.org/schema",
    "id": "GenerateCustomComponent",
    "title": "Generate Custom Component",
    "type": "object",
    "properties": {
        "name": {
            "description": "The name for the custom component.",
            "type": "string",
            "x-prompt": "What is the name for the custom component?"
        },
        "path": {
            "type": "string",
            "format": "path",
            "description": "The path at which to create the component file, relative to the current workspace. Default is a folder with the same name as the component in the project root.",
            "visible": false
        }
    },
    "required": [
        "name"
    ]
}

2)..schematics / ng-generate / customComponent / schema.ts

import { Schema as ComponentSChema } from '@schematics/angular/component/schema';

export interface Schema extends ComponentSChema {
    // The name of the custom component
    name: string;
}

2)..schematics / ng-generate / customComponent / index.ts

import {
  Rule, Tree, SchematicsException,
  apply, url, applyTemplates, move,
  chain, mergeWith
} from '@angular-devkit/schematics';

import { strings, experimental, normalize } from '@angular-devkit/core';

import { Schema as CustomSchema } from './schema';

export function generate(options: CustomSchema): Rule {
    return (tree: Tree) => {
        const workspaceConfig = tree.read('/angular.json'); // will return null when using schematics command but will work when using ng g
        console.log('workspaceConfig::', workspaceConfig);
        console.log('path:', options.path); // will be undefined when using schematics command but will work when using ng g
        
        // from now following along with angular docs with slight modifications. 
        if (workspaceConfig && !options.path) {
            const workspaceContent = workspaceConfig.toString();
            console.log('workspaceContent::', workspaceContent);
            
            const workspace: experimental.workspace.WorkspaceSchema = JSON.parse(workspaceContent);
            console.log('workspace', workspace);
            
            options.project = workspace.defaultProject;
            const projectName = options.project as string;
            const project = workspace.projects[projectName];
            const projectType = project.projectType === 'application' ? 'app' : 'lib';
            console.log('projectType::', projectType);
            
            options.path = `${project.sourceRoot}/${projectType}`;
        }

        
        if (options.path) { 
           // this will be used by the ng g command
            const templateSource = apply(url('./files'), [
                applyTemplates({
                    classify: strings.classify,
                    dasherize: strings.dasherize,
                    name: options.name
                }),
                move(normalize(options.path as string))
            ]);
            return chain([
                mergeWith(templateSource)
            ]);
        } else {
            // this will be used by the schematics command
            const templateSource = apply(url('./files'), [
                applyTemplates({
                    classify: strings.classify,
                    dasherize: strings.dasherize,
                    name: options.name
                })
            ]);
            return chain([
                mergeWith(templateSource)
            ]);
        }
    };
}