是否有TypeScript的代码生成API?

Lie*_*ero 13 t4 code-generation roslyn typescript

当我需要生成一些C#代码,例如来自xsd schema的DTO类或excel表时,我使用了一些roslyn API.

打字稿是否有类似的东西?

NSj*_*nas 15

尝试ts-morph.只使用它大约一个小时,但它似乎真的有能力.

import {Project, Scope, SourceFile} from "ts-morph";

const project = new Project();
const sourceFile = project.createSourceFile(`./target/file.ts`);

const classDeclaration = sourceFile.addClass({
    name: 'SomeClass'
});

const constr = classDeclaration.addConstructor({});
const param = constr.addParameter({
  name: 'myProp',
  type: string
});

constr.setBodyText('this.myProp = myProp');

classDeclaration.addProperty({
    name: 'myProp',
    type: 'string',
    initializer: 'hello world!',
    scope: Scope.Public
});
sourceFile.formatText();
console.log(sourceFile.getText());
Run Code Online (Sandbox Code Playgroud)

  • 经过这个库的更长时间后,我可以确认它是真正的交易.还有一些错误,但肯定有很多承诺.作者确实做得很好 (3认同)
  • 作为最初的提问者,我可以确认,我最终使用了 ts-morph。我尝试了原始 typescript 编译器 api,但它的级别太低,我最终编写了辅助函数,它的功能完全符合 ts-morh 的功能。 (2认同)

cod*_*ion 8

截至2018年10月,您可以为此使用标准TypeScript API

import ts = require("typescript");

function makeFactorialFunction() {
  const functionName = ts.createIdentifier("factorial");
  const paramName = ts.createIdentifier("n");
  const parameter = ts.createParameter(
    /*decorators*/ undefined,
    /*modifiers*/ undefined,
    /*dotDotDotToken*/ undefined,
    paramName
  );

  const condition = ts.createBinary(
    paramName,
    ts.SyntaxKind.LessThanEqualsToken,
    ts.createLiteral(1)
  );

  const ifBody = ts.createBlock(
    [ts.createReturn(ts.createLiteral(1))],
    /*multiline*/ true
  );
  const decrementedArg = ts.createBinary(
    paramName,
    ts.SyntaxKind.MinusToken,
    ts.createLiteral(1)
  );
  const recurse = ts.createBinary(
    paramName,
    ts.SyntaxKind.AsteriskToken,
    ts.createCall(functionName, /*typeArgs*/ undefined, [decrementedArg])
  );
  const statements = [ts.createIf(condition, ifBody), ts.createReturn(recurse)];

  return ts.createFunctionDeclaration(
    /*decorators*/ undefined,
    /*modifiers*/ [ts.createToken(ts.SyntaxKind.ExportKeyword)],
    /*asteriskToken*/ undefined,
    functionName,
    /*typeParameters*/ undefined,
    [parameter],
    /*returnType*/ ts.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
    ts.createBlock(statements, /*multiline*/ true)
  );
}

const resultFile = ts.createSourceFile(
  "someFileName.ts",
  "",
  ts.ScriptTarget.Latest,
  /*setParentNodes*/ false,
  ts.ScriptKind.TS
);
const printer = ts.createPrinter({
  newLine: ts.NewLineKind.LineFeed
});
const result = printer.printNode(
  ts.EmitHint.Unspecified,
  makeFactorialFunction(),
  resultFile
);

console.log(result);
Run Code Online (Sandbox Code Playgroud)

在这里拍摄:https : //github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-creating-and-printing-a-typescript-ast


bas*_*rat 5

打字稿是否有类似的东西

还没有,但TypeScript团队正在为插件打开发射器(那是什么),这将使这成为一个受支持的场景:https://github.com/Microsoft/TypeScript/issues/5595