Is there code generation API for TypeScript?

前端 未结 5 2108
不知归路
不知归路 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条回答
  •  情歌与酒
    2021-02-12 12:04

    Try ts-morph. Only been working with it for about an hour but it seems really capable.

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

提交回复
热议问题