tsgen2

1.0.4 • Public • Published

TsGen

About:

Generate typescript code programatically.

Installation:

npm install --save tsgen2

Usage:

Start creating a source generator object:

import * as path from 'path'
import { TsGenSource } from 'tsgen2/TsGenSource'

const file = path.resolve("./file.ts")
const source = new TsGenSource(file)

Then programatically add imports, functions, classes, etc. to this source object:

source.addImport(new TsGenImport("* as fs", "fs"))
source.addImport(new TsGenImport("Injectable", "@angular/core"))

const clazz = new TsGenClass("MyService", {exportable: true})
source.addClass(clazz)
clazz.addDecorator("@Injectable()")

const construct = new TsGenConstructor();
construct.addParameter(new TsGenParam("param", "number", false, "private"))
clazz.setConstructor(construct);

const method = new TsGenMethod("add");
method.addParameter(new TsGenParam("x", "number"));
method.addParameter(new TsGenParam("y", "number"));
method.addToBody("return x+y;");
clazz.addMethod(method);

Finally, save the generated code to a file

source.save()

or simply generate its string representation source.toString().

This example produces the following output

import * as fs from 'fs'
import { Injectable } from '@angular/core'

@Injectable()
export class MyService {
    constructor(private param: number) {
    }
    add(x: number, y: number) {
        return x + y;
    }

}

which obviously is a simple example.

License

MIT

Credits

Josep Mulet (pep.mulet@gmail.com)

Dependencies (1)

Dev Dependencies (0)

    Package Sidebar

    Install

    npm i tsgen2

    Weekly Downloads

    7

    Version

    1.0.4

    License

    ISC

    Unpacked Size

    50.7 kB

    Total Files

    51

    Last publish

    Collaborators

    • jmulet