Skip to content
Reference

JSX renderer

Reference for kubb/jsx, backed by @kubb/renderer-jsx: the jsxRenderer, the tsconfig setup, and the props of every built-in component.

kubb/jsx lets you write a template's files as JSX instead of ast.factory node builders.

Renderers

A renderer turns what a template returns into FileNodes. Kit renders JSX with jsxRenderer unless you pass another renderer, so addTemplate(template) is enough for a JSX template. A template that returns FileNodes from ast.factory needs no renderer either. Pass addTemplate(template, { renderer }) only for another renderer, or renderer: null to skip rendering.

Template returns JSXjsxRendererFileNode listParser, such as parserTsGenerated file
jsxRenderer does not use React. Components run once as plain functions, so hooks, suspense, and class components do not work.

For another template format, pass createRenderer from kubb/kit a factory that returns { render, files, [Symbol.dispose] }.

Setup

Point tsconfig.json at the kubb/jsx runtime instead of React:

tsconfig.json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "kubb/jsx"
  }
}

jsxRenderer()

jsxRenderer() returns a renderer. Call render with a JSX element, then read files.

render.tsx
import { File, Function, Type, jsxRenderer } from 'kubb/jsx'

const renderer = jsxRenderer()

await renderer.render(
  <File baseName="petStore.ts" path="src/gen/petStore.ts">
    <Type export name="Pet">{'{ id: number; name: string }'}</Type>
    <Function export name="getPet" async>
      {"return fetch('/pets')"}
    </Function>
  </File>,
)

const files = renderer.files

Built-in components

Inside a code component, Code or Raw, <br /> adds a line break.

Choose a component

Everything inside a File is an import, an export, or a source block. Pick the source block by what the content is:

The content isUseBarrels list it
A declaration you write in JSXConst, Type or Function with exportYes, when exported
A declaration a printer or a template already printedCode with exportYes, when exported
Text that declares nothing, such as a statement or JSONRawNo
MarkdownA Markdown componentNo

Core

File

With baseName and path, File declares a generated file. Without them, it renders its children inline. Text directly in a File, outside Code or Raw, throws.

PropTypeDescription
baseName`${string}.${string}`The file name, such as petStore.ts
pathstringThe full output path
meta?object | nullMetadata for plugins to read
banner?string | nullText before the source blocks
footer?string | nullText after the source blocks
copy?string | nullAn absolute path of a file to copy into the output
inline?boolean | nullNever writes the file. Files that import from it get its declarations. See Inline sources.
children?KubbReactNodeThe file's sources, imports, and exports
<File baseName="petStore.ts" path="src/models/petStore.ts">
  <Type export name="Pet">
    {`{ id: number; name: string }`}
  </Type>
</File>

Code

A printed declaration in the enclosing File, such as a schema from a printer or a class built as text. It works for any language. For a declaration written in JSX, or a TypeScript type, put a JavaScript component directly in the File.

PropTypeDescription
namestringThe declared name, for barrels and deduplication
export?booleanLists the declaration in barrels. The text still needs its own export.
default?booleanMarks the declaration as the default export, which barrels skip
space?'type' | 'value'Whether the declaration is a type or a value. Defaults to 'value'. Imports and barrels of a 'type' print type.
children?KubbReactNodeThe printed declaration
<File baseName="pet.ts" path="src/gen/pet.ts">
  <Code name="petSchema" export>
    {printer.print(node)}
  </Code>
</File>

Raw

Text in the enclosing File that declares nothing, such as a statement like faker.seed(1), JSON, or markdown. Barrels leave it out.

PropTypeDescription
name?stringKeys deduplication, so a block several templates add to one file is written once
children?KubbReactNodeThe text, written as is
<File baseName="pet.ts" path="src/gen/pet.ts">
  <File.Import names={[{ name: 'faker', space: 'value' }]} path="@faker-js/faker" />
  <Raw name="faker-seed">{'faker.seed(1)'}</Raw>
</File>

Origin

Records where the sources inside it come from in the input, so tools can link generated code back to it. openapi-import uses this for go to definition. It works for every source block in a File, in any language.

You only need it when one template writes code for several parts of the input. Without it, a source gets the location of the node being generated. An inner Origin wins over an outer one.

PropTypeDescription
pointer?stringThe input location, in the form the adapter reads, such as #/paths/~1pets/get/responses/200
children?KubbReactNodeThe sources it applies to
<File baseName="getPets.ts" path="src/gen/getPets.ts">
  <Type export name="GetPetsResponses">
    {printer.print(responses)}
  </Type>
  <Origin pointer={response.pointer}>
    <Type export name="GetPetsStatus200">
      {printer.print(response.schema)}
    </Type>
  </Origin>
</File>

File.Import

An import at the top of the enclosing File.

PropTypeDescription
namesArray<{ name: string; alias?: string; space?: 'type' | 'value' }>The names to import. name is the name in the other module, 'default' for its default export or '*' for the whole module. alias is the local name.
pathstringThe module to import from
root?string | nullThe file path the import is relative to

Each name prints as type when its space is 'type'. A name without space is a value.

<File.Import names={[{ name: 'useState', space: 'value' }]} path="react" />
// import { useState } from 'react'

<File.Import names={[{ name: '*', alias: 'z', space: 'value' }]} path="zod" />
// import * as z from 'zod'

<File.Import names={[{ name: 'default', alias: 'useSWR', space: 'value' }]} path="swr" />
// import useSWR from 'swr'

<File.Import names={[{ name: 'Pet', space: 'type' }]} root={target.path} path={types.path} />
// import type { Pet } from './models/Pet'

File.Export

An export at the top of the enclosing File.

PropTypeDescription
namesArray<{ name: string; alias?: string; space?: 'type' | 'value' }>The names to export. { name: '*' } exports everything, and an alias on it exports the module under one name.
pathstringThe module to export from

A name without space is a value.

<File.Export names={[{ name: 'Pet', space: 'type' }]} path="./models/petStore" />
// export type { Pet } from './models/petStore'

<File.Export names={[{ name: '*', space: 'value' }]} path="./models/petStore" />
// export * from './models/petStore'

<File.Export names={[{ name: '*', alias: 'models', space: 'value' }]} path="./models" />
// export * as models from './models'

Schema

Prints node, adds the printer's imports, and calls children with the code. It renders nothing when the printer returns nothing.

PropTypeDescription
nodeSchemaNodeThe schema to print
printerPrinterThe printer, such as one built with createPrinter
children(code: string) => KubbReactNodeRenders the declarations for the code
<Schema node={node} printer={printer}>
  {(code) => (
    <Const export name="petSchema">
      {code}
    </Const>
  )}
</Schema>

JavaScript

The JavaScript components emit TypeScript. Each takes export?: boolean | null to add export, and JSDoc?: { comments?: Array<string | undefined> } | null for a JSDoc block.

A component directly in a File is its own source block, named after name. export puts it in barrels, unless it is also default. In an inline file, importing files use its body in place of its name.

<File baseName="pet.ts" path="src/zod/pet.ts">
  <Const export name="petSchema">{'z.object({ id: z.number() })'}</Const>
  <Type export name="Pet">{'z.infer<typeof petSchema>'}</Type>
</File>

Const

A const declaration, with the children as the initializer.

PropTypeDescription
namestringThe name
type?string | nullThe annotation after const name:
asConst?boolean | nullAdds as const after the initializer
<Const export name="petSchema" type="z.ZodType<Pet>">
  {`z.object({ id: z.number() })`}
</Const>
// export const petSchema: z.ZodType<Pet> = z.object({ id: z.number() })

Function

A function declaration, with the children as the body.

PropTypeDescription
namestringThe name
default?boolean | nullAdds default after export
async?boolean | nullAdds async and wraps returnType in Promise<…>
params?string | nullThe parameter list
generics?string | Array<string> | nullThe type parameters. An array joins with commas.
returnType?string | nullThe return type after :
<Function export async name="getPet" generics={['TData = Pet']} params="petId: string" returnType="TData">
  {'return client.get("/pets/" + petId)'}
</Function>
// export async function getPet<TData = Pet>(petId: string): Promise<TData> { … }

Function.Arrow

An arrow function in a const. It takes every Function prop, plus singleLine?: boolean | null for an expression body without braces.

<Function.Arrow export name="double" params="n: number" returnType="number" singleLine>
  {`n * 2`}
</Function.Arrow>
// export const double = (n: number): number => n * 2

Type

A type alias or an interface, with the children as the type. Barrels re-export it with export type.

PropTypeDescription
namestringThe alias name
syntax?'type' | 'interface''interface' declares interface Name { … }, so the children must be an object type. Defaults to 'type'.
<Type export name="PetId">
  {`string | number`}
</Type>
// export type PetId = string | number

<Type export name="Pet" syntax="interface">
  {`{ id: number }`}
</Type>
// export interface Pet { id: number }

Markdown

Each Markdown component emits its own source block, so put it directly in a File, not in Code or Raw. Name the file .md so parserMd prints it.

docs.tsx
import { Callout, File, Frontmatter, Heading, List, Paragraph, jsxRenderer } from 'kubb/jsx'

const renderer = jsxRenderer()

await renderer.render(
  <File baseName="pets.md" path="src/docs/pets.md">
    <Frontmatter data={{ title: 'Pets', layout: 'doc' }} />
    <Heading level={2}>Pets</Heading>
    <Paragraph>{'A pet object with an id and a name.'}</Paragraph>
    <List items={['id: number', 'name: string']} />
    <Callout type="tip">Keep the generator hot with kubb generate --watch.</Callout>
  </File>,
)

Callout

A GitHub alert in > [!TYPE] syntax.

PropTypeDescription
type'tip' | 'note' | 'important' | 'warning' | 'caution'The alert kind, printed in uppercase
title?string | nullText on the marker line
childrenstringThe body. Each line gets a > prefix.
<Callout type="warning" title="Heads up">Breaking change in v6.</Callout>
// > [!WARNING] Heads up
// > Breaking change in v6.

Frontmatter

YAML frontmatter between --- fences, as the first child of the File. An empty data prints nothing.

PropTypeDescription
dataRecord<string, unknown>The object to write as YAML

Heading

An ATX heading, such as ## Installation for level={2}.

PropTypeDescription
level1 | 2 | 3 | 4 | 5 | 6The number of # characters
childrenstringThe heading text

List

A list with one item per line.

PropTypeDescription
itemsReadonlyArray<string>The items
ordered?boolean | nullNumbers the items 1., 2., and so on. Default: a - list.

Paragraph

A paragraph. Inline Markdown passes through as written.

PropTypeDescription
childrenstringThe paragraph text

JSX

Jsx

Embeds a raw JSX string, fragments included, such as a component body in a Function. The children must be one plain string.

PropTypeDescription
children?stringThe JSX source, written as is
<Function name="MyComponent" export>
  <Jsx>{'return (\n  <>\n    <div>Hello</div>\n  </>\n)'}</Jsx>
</Function>

Less common cases

Inline sources

When a plugin writes a File with copy or inline, Kubb copies or absorbs it instead of printing it.

  • copy is an absolute path to copy into the output, through the parser's copy hook if it has one. Its sources count for barrels but are not printed.
  • inline means Kubb never writes the file. A file that imports from it gets the Const or Type and the imports its body needs. A type used once, or a bare name, goes in place of the name. Anything else becomes one local declaration, numbered on a clash, such as Response2. Importing a Function or printed Code reports a problem, because neither has a body.
<File baseName="AddPet.ts" path="src/gen/models/AddPet.ts" inline>
  <Type export name="AddPetStatus200">
    {'Pet'}
  </Type>
</File>

The parser's inline(files) hook runs before barrels, and only its files absorb inline sources. parserTs and parserTsx have it. An inline set to an InlineLanguage object still works for older parsers, but it is deprecated.

With the kubb/jsx setup, .tsx files load jsx-runtime and jsx-dev-runtime from kubb/jsx.