Skip to content

Vectutil/func2md

Repository files navigation

func2md

从 JSDoc 注释和 TypeScript 类型生成 VitePress 文档的 CLI 工具和 Vite 插件。

功能特性

  • 扫描指定目录中的 JavaScript/TypeScript 函数
  • 解析 JSDoc 注释提取函数信息
  • 生成兼容 VitePress 的 Markdown 文档
  • 支持自定义扫描目录和输出位置
  • 支持 Vite 插件模式或独立 CLI 模式使用

安装

npm install func2md

使用方式

方式一:Vite 插件

vite.config.ts 中配置:

// vite.config.ts
import { defineConfig } from 'vite'
import func2md from 'func2md'

export default defineConfig({
  plugins: [
    func2md({
      srcDir: 'src',     // 源目录
      outDir: 'docs',    // 输出目录
      watch: false       // 是否监听变化
    })
  ]
})

方式二:CLI 命令行

无需 Vite,直接在命令行使用:

# 使用默认配置(扫描 src 目录,输出到 docs)
npx func2md

# 自定义目录
npx func2md --src-dir=lib --out-dir=documentation

或在 package.json 中添加脚本:

{
  "scripts": {
    "docs": "func2md --src-dir=src --out-dir=docs"
  }
}

方式三:JavaScript API

在代码中直接调用:

import { scanAndGenerateDocs, getRecords } from 'func2md'

// 生成文档
await scanAndGenerateDocs('./src', './docs')

// 读取生成的 _pages.js 记录
const pages = getRecords({ outDir: './docs' })
const mathGroup = getRecords({ outDir: './docs', text: '数学' })

配置选项

选项 类型 默认值 说明
srcDir string 'src' 源目录路径
outDir string 'docs' 输出目录路径
watch boolean false 是否监听文件变化(仅 Vite 插件模式)

JSDoc 格式

插件支持以下 JSDoc 标签与行为:

  • @title:生成文档的主标题(H1)。未填写时使用注释第一行作为标题。
  • @MenuTitle:生成到 _pages.js 的菜单标题,用于侧边栏条目显示。
  • @param {type} name - desc:生成「参数」表格行。
  • @returns / @return:生成「返回值」区块。
  • @example:生成「示例」代码块。
  • 注释中位于第一个标签(@param/@returns/@example)之前的文本,会作为「说明」内容。

示例:

/**
 * @title 两数相加
 * 将两个数字相加
 * @MenuTitle 数学/加法
 * @param {number} a - 第一个数字
 * @param {number} b - 第二个数字
 * @returns {number} 两数之和
 * @example
 * import { add } from './math'
 * const result = add(1, 2) // 返回 3
 */
function add(a, b) {
  return a + b
}

生成的文档格式

插件生成以下结构的 Markdown 文件:

# 函数标题

## 说明

函数描述...

## 参数

| 名称 | 类型 | 描述 |
|------|------|------|
| paramName | `type` | 参数描述 |

## 返回值

- 类型: `returnType`
- 描述: 返回值描述

## 示例

```ts
// 示例代码

生成的 _pages.js 仅导出 pages 数组,便于 VitePress 直接引入。需要筛选记录时请使用库导出的 getRecords()


## 开发

### 构建项目

```bash
npm run build

运行测试

npm run test

运行测试并生成覆盖率报告

npm run test:coverage

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published