Is there code generation API for TypeScript?

前端 未结 5 2123
不知归路
不知归路 2021-02-12 11:17

When I needed to generate some C# code, for example DTO classes from xsd schema, or an excel table, I\'ve used some roslyn API\'s.

Is there something simmilar for typescr

5条回答
  •  Happy的楠姐
    2021-02-12 11:53

    as of Oct-2018 You could use standard TypeScript API for that

    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);

    Taken here: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-creating-and-printing-a-typescript-ast

提交回复
热议问题