javascripttypescriptvue.jsmarkdownvitepress

Is it possible to render TS types or values of variables inside markdown files using static site generators like VitePress?


I want to create a documentation using Vitepress ( or similiar ). This app uses a package which contains types and Zod schemas. The root library index.ts could be

import { z } from 'zod';

const userSchema = z
  .object({
    username: z.string().min(1),
  })
  .strict();

type User = z.infer<typeof userSchema>;

export { userSchema, type User }

Is there a way to either render the schema or the type inside the markdown file?

Maybe with the help of Vue files ( VitePress )

I just want to describe the schema or type but don't want to copy paste all the fields from it because then I have to take care that everything is in sync.


Solution

    1. Use https://www.npmjs.com/package/zod-to-ts to convert your schema to a runtime typescript-lang string
    2. Use ts-vue Code Blocks ro render it
    <script setup lang="ts">
    import { printNode, zodToTs } from 'zod-to-ts'
    import { UserSchema } from './schemas'
    
    const identifier = 'User'
    const { node } = zodToTs(UserSchema, identifier)
    const nodeString = printNode(node)
    </script>
    
    ```ts-vue
    // {{ identifier }} Schema
    {{ nodeString }}
    ```