4

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.

baitendbidz
  • 187
  • 3
  • 19
  • You have the type at runtime in the form of a zod schema. – kelsny Apr 11 '23 at 14:01
  • yes I do. And VitePress should render the structure of the schema or type ( one is fine ) – baitendbidz Apr 11 '23 at 14:05
  • Okay this is not as easy as I thougnt, you'll need either a runtime highlighter or compile-time interface generation (via a vitepress plugin like https://github.com/vueuse/vueuse/blob/02ccce9ad961ef2c9fd6a3ff182daf6e4157407a/packages/.vitepress/plugins/markdownTransform.ts#L2). – Dimava Apr 13 '23 at 10:45

1 Answers1

1
  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 }}
```
Dimava
  • 7,654
  • 1
  • 9
  • 24
  • very nice! Do you know if syntax highlighting is possible? because `ts-vue` is required to work but then you loose support for TS syntax highlighting – baitendbidz Apr 12 '23 at 20:57
  • @baitendbidz docs: `To enable Vue-style interpolation inside fences, you can append the language with the -vue suffix, e.g. js-vue` so that should be default TS syntax highlighting – Dimava Apr 12 '23 at 21:27
  • I tried to setup a Stackblitz example, I hope this helps https://stackblitz.com/edit/vite-hrkkdg?file=package.json – baitendbidz Apr 13 '23 at 05:35
  • if you get an error, I had to install `typescript` and then it worked for me. Somehow I can't save a new version anymore – baitendbidz Apr 13 '23 at 05:41