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());
截至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);在这里拍摄:https : //github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-creating-and-printing-a-typescript-ast
打字稿是否有类似的东西
还没有,但TypeScript团队正在为插件打开发射器(那是什么),这将使这成为一个受支持的场景:https://github.com/Microsoft/TypeScript/issues/5595
| 归档时间: | 
 | 
| 查看次数: | 5661 次 | 
| 最近记录: |