原理图适用于原理图项目,但不适用于角度项目

时间:2018-10-11 13:02:11

标签: angular npm angular-cli angular-schematics

我正在构建自己的自定义原理图。在我的原理图项目上,一切都工作正常。但是,当我在一个有角度的项目中导入该项目并尝试生成一个组件时,出现错误。 您可以在npm上找到该软件包:

"akasuaptics": "~0.0.1"

在我的原理图项目中,我尝试使用:

生成它
schematics .:page --> Schematic input does not validate against the schema [...] Data path "" should have required property 'name'
schematics .:page test--> Schematic input does not validate against the schema [...] Data path "" should have required property 'name'
schematics .:page --name=test -->success

在我的有角项目中,我尝试使用:

生成
ng generate akasuaptics:page --> Cannot read property 'split' of undefined
ng generate akasuaptics:page test --> Cannot read property 'split' of undefined
ng generate akasuaptics:page --name=test -->Cannot read property 'split' of undefined

enter image description here

schema.json

{
  "$schema": "http://json-schema.org/schema",
  "id": "SchematicsPage",
  "title": "Suaptics Page Options Schema",
  "type": "object",
  "properties": {
    "path": {
      "type": "string",
      "description": "The path to create the page.",
      "default": "app/pages",
      "visible": false
    },
    "sourceDir": {
      "type": "string",
      "description": "The path of the source directory.",
      "default": "src",
      "alias": "sd",
      "visible": false
    },
    "appRoot": {
      "type": "string",
      "description": "The root of the application.",
      "visible": false
    },
    "name": {
      "type": "string",
      "description": "The name of the page."
    },
    "inlineStyle": {
      "description": "Specifies if the style will be in the ts file.",
      "type": "boolean",
      "default": false,
      "alias": "is"
    },
    "inlineTemplate": {
      "description": "Specifies if the template will be in the ts file.",
      "type": "boolean",
      "default": false,
      "alias": "it"
    },
    "viewEncapsulation": {
      "description": "Specifies the view encapsulation strategy.",
      "enum": ["Emulated", "Native", "None"],
      "type": "string",
      "alias": "ve"
    },
    "changeDetection": {
      "description": "Specifies the change detection strategy.",
      "enum": ["Default", "OnPush"],
      "type": "string",
      "default": "Default",
      "alias": "cd"
    },
    "prefix": {
      "type": "string",
      "description": "The prefix to apply to generated selectors.",
      "default": "page",
      "alias": "p"
    },
    "styleext": {
      "description": "The file extension to be used for style files.",
      "type": "string",
      "default": "scss"
    },
    "spec": {
      "type": "boolean",
      "description": "Specifies if a spec file is generated.",
      "default": true
    },
    "flat": {
      "type": "boolean",
      "description": "Flag to indicate if a dir is created.",
      "default": false
    },
    "skipImport": {
      "type": "boolean",
      "description": "Flag to skip the module import.",
      "default": true
    },
    "selector": {
      "type": "string",
      "description": "The selector to use for the component."
    },
    "module":  {
      "type": "string",
      "description": "Allows specification of the declaring module.",
      "alias": "m"
    },
    "export": {
      "type": "boolean",
      "default": false,
      "description": "Specifies if declaring module exports the component."
    }
  },
  "required": [
    "name"
  ]
}

index.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const ts = require("typescript");
const stringUtils = require("../strings");
const ast_utils_1 = require("../utility/ast-utils");
const change_1 = require("../utility/change");
const find_module_1 = require("../utility/find-module");
function addDeclarationToNgModule(options) {
    return (host) => {
        if (options.skipImport || !options.module) {
            return host;
        }
        const modulePath = options.module;
        const text = host.read(modulePath);
        if (text === null) {
            throw new schematics_1.SchematicsException(`File ${modulePath} does not exist.`);
        }
        const sourceText = text.toString('utf-8');
        const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
        const componentPath = `/${options.sourceDir}/${options.path}/`
            + (options.flat ? '' : stringUtils.dasherize(options.name) + '/')
            + stringUtils.dasherize(options.name)
            + '.page';
        const relativePath = find_module_1.buildRelativePath(modulePath, componentPath);
        const classifiedName = stringUtils.classify(`${options.name}Page`);
        const declarationChanges = ast_utils_1.addDeclarationToModule(source, modulePath, classifiedName, relativePath);
        const declarationRecorder = host.beginUpdate(modulePath);
        for (const change of declarationChanges) {
            if (change instanceof change_1.InsertChange) {
                declarationRecorder.insertLeft(change.pos, change.toAdd);
            }
        }
        host.commitUpdate(declarationRecorder);
        if (options.export) {
            // Need to refresh the AST because we overwrote the file in the host.
            const text = host.read(modulePath);
            if (text === null) {
                throw new schematics_1.SchematicsException(`File ${modulePath} does not exist.`);
            }
            const sourceText = text.toString('utf-8');
            const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
            const exportRecorder = host.beginUpdate(modulePath);
            const exportChanges = ast_utils_1.addExportToModule(source, modulePath, stringUtils.classify(`${options.name}Page`), relativePath);
            for (const change of exportChanges) {
                if (change instanceof change_1.InsertChange) {
                    exportRecorder.insertLeft(change.pos, change.toAdd);
                }
            }
            host.commitUpdate(exportRecorder);
        }
        return host;
    };
}
function buildSelector(options) {
    let selector = stringUtils.dasherize(options.name);
    if (options.prefix) {
        selector = `${options.prefix}-${selector}`;
    }
    return selector;
}
function default_1(options) {
    const sourceDir = options.sourceDir;
    if (!sourceDir) {
        throw new schematics_1.SchematicsException(`sourceDir option is required.`);
    }
    return (host, context) => {
        options.selector = options.selector || buildSelector(options);
        options.path = options.path ? core_1.normalize(options.path) : options.path;
        options.module = find_module_1.findModuleFromOptions(host, options);
        const templateSource = schematics_1.apply(schematics_1.url('./files'), [
            options.spec ? schematics_1.noop() : schematics_1.filter(path => !path.endsWith('.spec.ts')),
            options.inlineStyle ? schematics_1.filter(path => !path.endsWith('.__styleext__')) : schematics_1.noop(),
            options.inlineTemplate ? schematics_1.filter(path => !path.endsWith('.html')) : schematics_1.noop(),
            schematics_1.template(Object.assign({}, stringUtils, { 'if-flat': (s) => options.flat ? '' : s }, options)),
            schematics_1.move(sourceDir),
        ]);
        return schematics_1.chain([
            schematics_1.branchAndMerge(schematics_1.chain([
                addDeclarationToNgModule(options),
                schematics_1.mergeWith(templateSource),
            ])),
        ])(host, context);
    };
}
exports.default = default_1;

__ name @ dasherize __。page.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import {Mediator,iMediatorable} from 'mediator_akasuap';


import { LoggerService } from '@core/logger/logger.service';


@Component({
  selector: '<%= selector %>',
  templateUrl: './<%= dasherize(name) %>.page.html',
  styleUrls : ['./<%= dasherize(name) %>.page.scss']
})
export class <%= classify(name) %>Page implements OnInit, OnDestroy,iMediatorable {
  private mediator = Mediator.getInstance();
  constructor( private logger: LoggerService) {

  }
  public getName(){
      return "<%= classify(name) %>Page"
  }
  public receive(msg: string, data: any){
    switch(msg){

    }
  }
  public ngOnInit() {
    this.mediator.register(this);
    this.logger.info('<%= classify(name) %>Page: ngOnInit()');
  }

  public ngOnDestroy() {
    this.mediator.unregister(this.getName());
    this.logger.info('<%= classify(name) %>Page: ngOnDestroy()');
  }
}

因为这是我的第一个原理图项目,所以我真的不知道该错误的查找位置。我有点cho异,在原理图项目上一切正常,但在有角度的项目上一切正常。

2 个答案:

答案 0 :(得分:0)

一些观察(如果您有可共享的公共回购链接,将有助于确认行为):

首先,要传递@Before public void setup() { final ActivityController<MainActivity> activityController = buildActivity(MainActivity.class); Robolectric.getForegroundThreadScheduler().pause(); activityController.setup(); Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable(); Robolectric.getForegroundThreadScheduler().unPause(); } 参数而不必指定键和值(name而不是ng generate page test),我通常必须配置ng generate page --name=test通过位置schema.json参数设置默认值的文件:

argv

您可以在simple-schematic project of my github repo中看到一个更完整,更有效的示例。

对于您提出的第二个问题,我能够使用提供的示意图命令 "name": { "description": "The name of the workspace", "type": "string", "$default": { "$source": "argv", "index": 0 } } 安装NPM软件包并创建一个页面,而没有出现任何错误。您还在机器上遇到此错误吗?

答案 1 :(得分:0)

我刚才自己偶然发现了这个错误。当我执行

    <h3>results show here...</h3>
    <pre id=show_result1>
    </pre>
通过另一个通过npm链接链接的项目中的

,例如ng g @myown/schematics:something 将读为null。请注意,该文件仍可以通过host.read('package.json')看到。

当我从实际安装软件包的存储库中执行命令时,不仅可以链接它,而且可以正常工作。

我想这是写权限的问题,出于安全原因,Angular Builder的树不应该访问主项目之外的文件