6.9.0 • Published 17 days ago

ts-poet v6.9.0

Weekly downloads
29,112
License
Apache-2.0
Repository
github
Last release
17 days ago

npm CircleCI

Overview

ts-poet is a TypeScript code generator that is a fancy wrapper around template literals.

Here's some example HelloWorld output generated by ts-poet:

import { Observable } from "rxjs/Observable";

export class Greeter {
  private name: string;

  constructor(private name: string) {}

  greet(): Observable<string> {
    return Observable.from(`Hello $name`);
  }
}

And this is the code to generate it with ts-poet:

import { code, imp } from "ts-poet";

// Use `imp` to declare an import that will conditionally auto-imported
const Observable = imp("@rxjs/Observable");

// Optionally create helper consts/methods to incrementally create output 
const greet = code`
  greet(): ${Observable}<string> {
    return ${Observable}.from(\`Hello $name\`);
  }
`;

// Combine all of the output (note no imports are at the top, they'll be auto-added)
const greeter = code`
export class Greeter {

  private name: string;

  constructor(private name: string) {
  }

  ${greet}
}
`;

// Generate the full output, with imports
const output = greeter.toStringWithImports("Greeter");

I.e. the primary value provided by ts-poet is:

  1. "Auto import" only actually-used symbols

    I.e. if you use imp to define the modules/imports you need in your generated code, ts-poet will create the import stanza at the top of the file.

    This can seem minor, but it facilitates decomposition of your code generation code, so that you can have multiple levels of helper methods/etc. that can return code template literals that embed both the code itself and the necessary type imports.

    And when the final file is generated, ts-poet will collect and emit the necessary imports.

  2. Includes any other conditional output (see later), as/if needed.

  3. Formats the output with dprint-node

    (ts-poet originally used prettier, but prettier is dramatically slower than dprint-node, and had become the bottleneck in several projects' code generation steps. So now we use dprint-node configured to generate "prettier-ish" output.)

Import Specs

Given the primary goal of ts-poet is to manage imports for you, there are several ways of specifying imports to the imp function:

  • imp("Observable@rxjs") --> import { Observable } from "rxjs"
  • imp("Observable:CustomizedObservable@rxjs") --> import { Observable as CustomizedObservable } from "rxjs"
  • imp("t:Observable@rxjs") --> import type { Observable } from "rxjs"
  • imp("t:Observable:CustomizedObservable@rxjs") --> import type { Observable as CustomizedObservable } from "rxjs"
  • imp("Observable@./Api") --> import { Observable } from "./Api"
  • imp("Observable*./Api") --> import * as Observable from "./Api"
  • imp("Observable=./Api") --> import Observable from "./Api"
  • imp("@rxjs/Observable") --> import { Observable } from "rxjs/Observable"
  • imp("*rxjs/Observable") --> import * as Observable from "rxjs/Observable"
  • imp("@Api") --> import { Api } from "Api"
  • imp("describe+mocha") --> import "mocha"

Avoiding Import Conflicts

Sometimes code generation output may declare a symbol that conflicts with an imported type (usually for generic names like Error).

ts-poet will automatically detect and avoid conflicts if you tell it which symbols you're declaring, i.e.:

const bar = imp('Bar@./bar');
const output = code`
  class ${def("Bar")} extends ${bar} {
     ...
  }
`;

Will result in the imported Bar symbol being remapped to Bar1 in the output:

import { Bar as Bar1 } from "./bar";
class Bar extends Bar1 {}

This is an admittedly contrived example for documentation purposes, but can be really useful when generating code against arbitrary / user-defined input (i.e. a schema that happens to uses a really common term).

Conditional Output

Sometimes when generating larger, intricate output, you want to conditionally include helper methods. I.e. have a convertTimestamps function declared at the top of your module, but only actually include that function if some other part of the output actually uses timestamps (which might depend on the specific input/schema you're generating code against).

ts-poet supports this with a conditionalOutput method:

const convertTimestamps = conditionalOutput(
  // The string to output at the usage site
  "convertTimestamps",
  // The code to conditionally output if convertTimestamps is used
  code`function convertTimestamps() { ...impl... }`,
);

const output = code`
  ${someSchema.map(f => {
    if (f.type === "timestamp") {
      // Using the convertTimestamps const marks it as used in our output
      return code`${convertTimestamps}(f)`;
    }
  })}
  // The .ifUsed result will be empty unless `convertTimestamps` has been marked has used
  ${convertTimestamps.ifUsed}
`;

And your output will have the convertTimestamps declaration only if one of the schema fields had a timestamp type.

This helps cut down on unnecessary output in the code, and compiler/IDE warnings like unused functions.

Literals

If you want to add a literal value, you can use literalOf and arrayOf:

codeoutput
let a = ${literalOf('foo')}let a = 'foo';
let a = ${arrayOf(1, 2, 3)}let a = [1, 2, 3];
let a = ${{foo: 'bar'}}let a = { foo: 'bar' };
let a = ${{foo: code`bar`}}let a = { foo: bar };

esModuleInterop Support

Unfortunately some dependencies need different imports based on your project's esModuleInterop setting.

For example, with protobufjs, the Reader symbol is imported differently:

// With esModuleInterop: true, need to use default import
// import m1 from "protobufjs"
// let r1: m1.Reader = ...
const r1 = imp("Reader@protobufjs")

// With esModuleInterop: false, need to use module star import
// import * as m1 from "protobufjs"
// let r1: m1.Reader = ...
const r2 = imp("Reader@protobufjs")

For these scenarios, you can use forceDefaultImport or forceModuleImport:

const Reader = imp("Reader@protobufjs")
const c = code`let r1: ${Reader} = ...`
const esModuleInterop = fromYourConfig();
console.log(c.toString(
  esModuleInterop
    ? { forceDefaultImport: ["protobufjs"] }
    : { forceModuleImport: ["protobufjs"] }
));

This is most useful for frameworks that generate code, and have to support downstream projects that might have either esModuleInterop setting.

History

ts-poet was originally inspired by Square's JavaPoet code generation DSL, which has a very "Java-esque" builder API of addFunction/addProperty/etc. that ts-poet copied in it's original v1/v2 releases.

JavaPoet's approach worked very well for the Java ecosystem, as it was providing three features:

  1. nice formatting (historically code generation output has looked terrible; bad formatting, bad indentation, etc.)
  2. nice multi-line string support, via appendLine(...).appendLine(...) style methods.
  3. "auto organize imports", of collecting imported symbols across the entire compilation unit of output, and organizing/formatting them at the top of the output file.

However, in the JavaScript/TypeScript world we have prettier for formatting, and nice multi-line string support via template literals, so really the only value add that ts-poet needs to provide is the "auto organize imports", which is what the post-v2/3.0 API has been rewritten (and dramatically simplified as a result) to provide.

6.8.2

17 days ago

6.9.0

17 days ago

6.8.1

29 days ago

6.8.0

30 days ago

6.7.0

3 months ago

6.5.0

10 months ago

6.6.0

8 months ago

6.4.1

1 year ago

6.4.0

1 year ago

6.3.0

1 year ago

6.2.1

1 year ago

6.2.0

1 year ago

5.1.0

2 years ago

6.1.0

2 years ago

5.2.0

2 years ago

5.0.1

2 years ago

5.0.0

2 years ago

6.0.1

2 years ago

6.0.0

2 years ago

4.12.0

2 years ago

4.14.0

2 years ago

4.15.0

2 years ago

4.13.0

2 years ago

4.11.0

2 years ago

4.9.0

2 years ago

4.10.0

2 years ago

4.8.0

2 years ago

4.7.0

2 years ago

4.6.1

3 years ago

4.6.0

3 years ago

4.5.0

3 years ago

4.4.1

3 years ago

4.4.0

3 years ago

4.3.3

3 years ago

4.3.2

3 years ago

4.3.1

3 years ago

4.3.0

3 years ago

4.2.0

3 years ago

3.3.1

3 years ago

3.3.0

3 years ago

4.1.0

3 years ago

4.0.0

3 years ago

3.2.2

4 years ago

3.2.1

4 years ago

3.2.0

4 years ago

3.1.0

4 years ago

1.0.1

4 years ago

3.0.0

4 years ago

3.0.0-beta.1

4 years ago

3.0.0-beta.0

4 years ago

3.0.0-alpha.8

4 years ago

3.0.0-alpha.7

4 years ago

3.0.0-alpha.6

4 years ago

3.0.0-alpha.5

4 years ago

3.0.0-alpha.4

4 years ago

3.0.0-alpha.3

4 years ago

3.0.0-alpha.2

4 years ago

3.0.0-alpha.1

4 years ago

3.0.0-alpha.0

4 years ago

2.1.0

4 years ago

2.0.0

4 years ago

1.0.0

5 years ago

0.6.0

5 years ago

0.5.5

5 years ago

0.5.4

5 years ago

0.5.3

5 years ago

0.5.1

5 years ago

0.5.0

5 years ago

0.4.5

5 years ago

0.4.4

5 years ago

0.4.3

5 years ago

0.4.2

5 years ago

0.4.1

5 years ago

0.4.0

5 years ago

0.3.0

5 years ago

0.2.6

5 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

6 years ago

0.2.1

6 years ago

0.2.0

6 years ago

0.1.0

6 years ago