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

huangapple go评论63阅读模式
英文:

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

问题

Sure, here is the translated text:

我想使用 Vitepress(或类似的工具)创建文档。此应用程序使用一个包,其中包含类型和Zod模式。根库的 index.ts 可能如下:

import { z } from 'zod';

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

type User = z.infer<typeof userSchema>;

export { userSchema, User }

有没有一种方法可以在 markdown 文件中渲染模式或类型?

也许可以借助 Vue 文件(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 &#39;zod&#39;;

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

type User = z.infer&lt;typeof userSchema&gt;;

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.

答案1

得分: 1

  1. 使用 https://www.npmjs.com/package/zod-to-ts 将您的模式转换为运行时 TypeScript 语言字符串。
  2. 使用 ts-vue Code Blocks 来呈现它。
&lt;script setup lang=&quot;ts&quot;&gt;
import { printNode, zodToTs } from &#39;zod-to-ts&#39;
import { UserSchema } from &#39;./schemas&#39;

const identifier = &#39;User&#39;
const { node } = zodToTs(UserSchema, identifier)
const nodeString = printNode(node)
&lt;/script&gt;

```ts-vue
// {{ identifier }} 模式
{{ nodeString }}
英文:
  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
&lt;script setup lang=&quot;ts&quot;&gt;
import { printNode, zodToTs } from &#39;zod-to-ts&#39;
import { UserSchema } from &#39;./schemas&#39;

const identifier = &#39;User&#39;
const { node } = zodToTs(UserSchema, identifier)
const nodeString = printNode(node)
&lt;/script&gt;

```ts-vue
// {{ identifier }} Schema
{{ nodeString }}
```

huangapple
  • 本文由 发表于 2023年4月10日 21:58:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定