ts-poet is a specialized code generation DSL (Domain Specific Language) for TypeScript, currently at version 6.12.0. It distinguishes itself by leveraging TypeScript's template literals to provide an intuitive, string-based approach to code generation, sidestepping the complexities of direct Abstract Syntax Tree (AST) manipulation. Its core strength lies in automatic import management, intelligently collecting and emitting necessary `import` statements, resolving symbol collisions, and simplifying conditional output. ts-poet also integrates `dprint-node` for fast and 'prettier-ish' code formatting, a significant differentiator from many generators that output unformatted or poorly formatted code. While inspired by JavaPoet's builder patterns in its earlier v1/v2 releases, the library has since evolved to a more streamlined, template-literal-centric API, making it highly adaptable for generating code from arbitrary schemas or user-defined inputs. The project maintains an active development status with consistent updates to support modern TypeScript features and ecosystem changes.
npm install ts-poetVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates `ts-poet` generating a TypeScript class with an interface, methods, and RxJS imports. It showcases `Code` template literals, automatic import management with `imp` and `def`, and `dprint-node` for formatting.
Rewrite code generation logic to use the `Code` template literal tag, `imp` for imports, and `def` for local definitions, as detailed in the current documentation.
Either configure dprint-node via `Code.toString({ dprintOptions: { ... } })` to match your desired style or create a `.dprint.json` file in your project root. Alternatively, you can disable `ts-poet`'s internal formatting and run a separate Prettier pass on the generated files.For problematic imports, consult `ts-poet`'s documentation on `imp`'s advanced usage. You might need to use `imp('Namespace.Member@module')` or `imp('Default:Alias@module')` to guide `ts-poet` in generating the correct import statement for the target environment and TypeScript configuration.Ensure your project is configured for ES modules (`"type": "module"` in `package.json` or `.mjs` extension) and use `import { ... } from 'ts-poet';`. Verify `ts-poet` is in `dependencies` and installed via `npm install` or `yarn add`.Install `dprint-node` as a dependency: `npm install dprint-node` or `yarn add dprint-node`. Ensure it's resolvable in your project's `node_modules`.
Always call `.toString()` on a `Code` instance to get the final generated string output. E.g., `const output = generatedCode.toString();`.
The `Code` function is a tagged template literal. Its arguments should primarily be `imp()` calls, `def()` calls, `Code` instances, or raw strings/numbers. Avoid complex logic or direct object access within the template literal; extract it outside if necessary.