This package, currently at version 3.2.4, generates TypeScript client code from a Swagger/OpenAPI 2.0 specification file. It leverages Mustache templates for highly customizable code generation, allowing developers to define their own class, method, and type structures. The generated code is built upon `superagent` for HTTP requests, making it adaptable for both Node.js and browser environments when used with bundlers like Browserify or Webpack. The project originated as a fork to streamline specific functionalities and integrate code quality checks via JSHint and code beautification with JS-Beautify. While not indicating a rapid release cadence, its focus on customization and robust template-driven generation makes it suitable for projects requiring tailored API clients.
npm install swagger-typescript-codegenVerified import paths — ran on the pinned version, not inferred.
This snippet demonstrates how to synchronously load a Swagger JSON specification from a file, parse it, and then use `swagger-typescript-codegen` to generate a TypeScript client class named 'TestClient', logging the output to the console.
Ensure your input specification strictly adheres to Swagger 2.0. If using OpenAPI 3.x, thoroughly test the generated code for correctness or consider alternative tools designed specifically for OpenAPI 3.x.
Utilize the `CodeGen.getCustomCode` function with tailored Mustache templates (`class`, `method`, `type`) to generate code that incorporates your desired HTTP client and its API calls.
For actual module dependencies of the generated client (e.g., `superagent` itself if not bundled), you will need to manually ensure they are installed and correctly bundled/imported in your consuming application. The `imports` option specifically handles type references.
Stick to `const CodeGen = require('swagger-typescript-codegen').CodeGen;` for consistent and reliable module loading, especially in Node.js environments. If working in a pure ESM context, manual wrapping or careful configuration might be needed.Verify the `swagger` JSON file's content and structure against the Swagger 2.0 specification. Ensure `fs.readFileSync` successfully reads the file and `JSON.parse` does not throw an error before passing the object to `CodeGen`.
Use the documented CommonJS import pattern: `const CodeGen = require('swagger-typescript-codegen').CodeGen;` to ensure `CodeGen` is correctly resolved as an object with the static `getTypescriptCode` method.Double-check the file path provided to `fs.readFileSync`. Ensure the file exists and the path is correct, or use an absolute path for robustness. Consider adding `process.cwd()` to construct the full path.