如何使用TypeScript编译器API向TypeScript类添加新属性?

问题描述

我尝试将新属性添加到我的awesome.model.ts文件中。

原始内容如下:

import { TagInterface,TagUIFieldsInterface } from './tag.interface';

export class Tag implements TagInterface {
  readonly api_endpoint = '/tag';
  id: ID;
  name: string;

  fields: FieldContainerInterface<TagUIFieldsInterface> = {
    // ...
  };

  init(data?: any): TagInterface {
    // ...
  }
}

我想在color_code: string;属性行之后添加一个新属性name。看起来像这样:

import { TagInterface,TagUIFieldsInterface } from './tag.interface';

export class Tag implements TagInterface {
  readonly api_endpoint = '/tag';
  id: ID;
  name: string;
  color_code: string;

  fields: FieldContainerInterface<TagUIFieldsInterface> = {
    // ...
  };

  init(data?: any): TagInterface {
    // ...
  }
}

在Schematics规则函数中,我尝试了此操作,但被卡住了:

export function model(_options: Schema,_fields?: Field[]): Rule {
  return (tree: Tree,_context: SchematicContext) => {
    // ...

    if (tree.exists(file)) {
      // read the file content and convert it to ts.Node[]
      const text = tree.read(file) ?? '';
      let sourceText = text.toString('utf-8');
      const sourceFile = ts.createSourceFile(file,sourceText,ts.ScriptTarget.Latest,true);
      const nodes = getSourceNodes(sourceFile);

      updateModelFields(file,nodes,_options);

      return;
    }
}

这是updateModelFields()函数:

export function updateModelFields(file: string,nodes: ts.Node[],options: Schema) {
  // find field definitions
  let propertyNodes: ts.Node[] = nodes.filter(n => n.kind === ts.SyntaxKind.PropertyDeclaration) || [];

  // create new property declaration
  const propertyDeclaration = ts.factory.createPropertyDeclaration(
    undefined,undefined,'color_code',ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),undefined
  );

  // add propertyDeclaration to nodes
  // ??
}

我尝试了几种添加新属性声明的方法,但总是失败。

当我尝试添加splice()函数时,它说:

Error: Debug Failure. False expression: Node must have a real position for this operation

有什么想法或最佳做法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)