name: 文档生成 description: 使用如JSDoc、Storybook或Docusaurus等工具,创建全面的技术文档,包括API文档、组件库、README文件、架构图和开发者指南。适用于文档化API、创建组件文档、编写README文件、生成API参考、文档化架构决策、创建入门指南、维护变更日志、文档化配置选项或构建开发者文档站点。
文档生成 - 创建清晰、可维护的文档
何时使用此技能
- 文档化REST或GraphQL API
- 使用Storybook创建组件库
- 编写全面的README文件
- 生成API参考文档
- 文档化架构决策(ADRs)
- 创建开发者入门指南
- 维护变更日志和发布说明
- 文档化配置和环境变量
- 使用Docusaurus构建文档站点
- 编写内联代码文档(JSDoc、TSDOC)
- 创建可视化架构图
- 文档化部署和操作流程
何时使用此技能
- 创建API文档、编写技术指南、生成代码文档或维护项目维基。
- 当处理相关任务或功能时
- 在需要此专业知识的开发过程中
使用时机:创建API文档、编写技术指南、生成代码文档或维护项目维基。
核心原则
- 文档即代码 - 版本控制、审查流程、自动生成
- 单一真实来源 - 尽可能从代码生成
- 保持新鲜 - 自动检查过时文档
- 示例优于解释 - 展示而非仅讲述
- 针对受众 - 为不同用户提供不同文档
API文档
1. OpenAPI/Swagger(REST API)
// ✅ JSDoc注释用于自动文档化
/**
* @swagger
* /users:
* get:
* summary: 列出所有用户
* description: 返回分页用户列表
* tags:
* - 用户
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* default: 1
* description: 页码
* - in: query
* name: limit
* schema:
* type: integer
* default: 20
* description: 每页项目数
* responses:
* 200:
* description: 成功
* content:
* application/json:
* schema:
* type: object
* properties:
* data:
* type: array
* items:
* $ref: '#/components/schemas/User'
* meta:
* type: object
* properties:
* page:
* type: integer
* total:
* type: integer
*/
app.get('/users', async (req, res) => {
// 实现
});
/**
* @swagger
* components:
* schemas:
* User:
* type: object
* required:
* - id
* - email
* properties:
* id:
* type: string
* example: "123"
* email:
* type: string
* format: email
* example: "user@example.com"
* name:
* type: string
* example: "John Doe"
* createdAt:
* type: string
* format: date-time
*/
// 设置Swagger UI
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
const options = {
definition: {
openapi: '3.0.0',
info: {
title: '我的API',
version: '1.0.0',
description: 'API文档',
},
servers: [
{
url: 'http://localhost:3000',
description: '开发服务器',
},
],
},
apis: ['./routes/*.ts'], // 带有@swagger注释的文件
};
const specs = swaggerJsdoc(options);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));
2. TypeDoc(TypeScript)
// ✅ JSDoc注释用于TypeDoc
/**
* 表示系统中的用户
*/
export interface User {
/** 唯一标识符 */
id: string;
/** 用户的电子邮件地址 */
email: string;
/** 用户的显示名称 */
name: string;
/** 账户创建时间戳 */
createdAt: Date;
}
/**
* 管理用户的服务
* @example
* ```typescript
* const userService = new UserService();
* const user = await userService.createUser({
* email: 'user@example.com',
* name: 'John Doe'
* });
* ```
*/
export class UserService {
/**
* 创建新用户
* @param data - 用户创建数据
* @returns 创建的用户
* @throws {ValidationError} 如果电子邮件无效
* @throws {ConflictError} 如果电子邮件已存在
*/
async createUser(data: CreateUserData): Promise<User> {
// 实现
}
/**
* 通过ID查找用户
* @param id - 用户ID
* @returns 用户对象或未找到时返回null
*/
async findById(id: string): Promise<User | null> {
// 实现
}
}
// typedoc.json
{
"entryPoints": ["src/index.ts"],
"out": "docs",
"plugin": ["typedoc-plugin-markdown"],
"excludePrivate": true,
"includeVersion": true
}
# 生成文档
npx typedoc
3. GraphQL文档(自动生成)
// 带有描述的GraphQL架构
const typeDefs = gql`
"""
表示系统中的用户
"""
type User {
"""唯一标识符"""
id: ID!
"""用户的电子邮件地址"""
email: String!
"""用户的显示名称"""
name: String!
"""此用户撰写的帖子"""
posts: [Post!]!
}
"""
创建新用户的输入
"""
input CreateUserInput {
"""有效的电子邮件地址"""
email: String!
"""显示名称(3-50个字符)"""
name: String!
"""密码(最少8个字符)"""
password: String!
}
type Query {
"""
通过ID获取单个用户
@example
query {
user(id: "123") {
id
email
name
}
}
"""
user(id: ID!): User
"""
列出所有用户(分页)
"""
users(limit: Int = 20, offset: Int = 0): [User!]!
}
`;
// GraphQL Playground自动提供交互式文档
代码文档
1. README.md模板
# 项目名称
简要描述此项目的功能。
## 功能
- 🚀 功能1
- 📦 功能2
- ⚡ 功能3
## 快速开始
```bash
# 安装依赖
npm install
# 运行开发服务器
npm run dev
# 运行测试
npm test
安装
详细安装说明…
使用
基本使用示例:
import { MyLibrary } from 'my-library';
const instance = new MyLibrary({
apiKey: 'your-key'
});
const result = await instance.doSomething();
API参考
参见API文档
配置
环境变量:
| 变量 | 描述 | 默认值 |
|---|---|---|
DATABASE_URL |
PostgreSQL连接字符串 | - |
PORT |
服务器端口 | 3000 |
NODE_ENV |
环境 | development |
贡献
许可证
MIT
### 2. **CHANGELOG.md**
```markdown
# 变更日志
本项目所有重要变更将记录在此文件中。
格式基于[Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
并遵循[语义化版本](https://semver.org/spec/v2.0.0.html)。
## [未发布]
### 新增
- 新功能X
- 支持Y
### 更改
- 改进Z的性能
### 弃用
- 旧API端点 /v1/users(使用 /v2/users替代)
### 移除
- 未使用的依赖foo
### 修复
- 身份验证流程中的错误
- WebSocket处理器中的内存泄漏
### 安全
- 更新具有安全漏洞的依赖项
## [2.1.0] - 2024-01-15
### 新增
- 用户个人资料自定义
- 深色模式支持
### 修复
- 登录重定向问题
## [2.0.0] - 2024-01-01
### 更改
- **破坏性变更**:将 `getUser()` 重命名为 `fetchUser()`
- **破坏性变更**:更改 `/api/users` 的响应格式
### 迁移指南
```typescript
// 之前
const user = await api.getUser(id);
// 之后
const user = await api.fetchUser(id);
### 3. **函数的JSDoc**
```typescript
/**
* 计算包括税费和运费的总价格
*
* @param items - 购物车项目数组
* @param options - 计算选项
* @param options.taxRate - 税率作为小数(例如,0.08表示8%)
* @param options.shippingCost - 固定运费
* @returns 总价格对象
*
* @example
* ```typescript
* const total = calculateTotal(
* [{ price: 10, quantity: 2 }],
* { taxRate: 0.08, shippingCost: 5 }
* );
* // 返回:{ subtotal: 20, tax: 1.6, shipping: 5, total: 26.6 }
* ```
*
* @throws {ValidationError} 如果项目数组为空
* @throws {ValidationError} 如果税率为负
*/
export function calculateTotal(
items: CartItem[],
options: {
taxRate: number;
shippingCost: number;
}
): TotalPrice {
// 实现
}
文档站点
1. VitePress(现代静态站点)
<!-- docs/index.md -->
---
layout: home
hero:
name: 我的库
text: 一个现代TypeScript库
tagline: 快速、类型安全且易于使用
actions:
- theme: brand
text: 开始使用
link: /guide/
- theme: alt
text: 在GitHub上查看
link: https://github.com/user/repo
features:
- title: 快速
details: 为性能而构建
- title: 类型安全
details: 完整的TypeScript支持
- title: 简单
details: 易于学习和使用
---
<!-- docs/guide/index.md -->
# 开始使用
## 安装
::: code-group
```bash [npm]
npm install my-library
yarn add my-library
pnpm add my-library
:::
快速示例
import { createClient } from 'my-library';
const client = createClient({
apiKey: process.env.API_KEY
});
const data = await client.fetch('/users');
下一步
```typescript
// docs/.vitepress/config.ts
import { defineConfig } from 'vitepress';
export default defineConfig({
title: '我的库',
description: '我的库文档',
themeConfig: {
nav: [
{ text: '指南', link: '/guide/' },
{ text: 'API', link: '/api/' },
{ text: '示例', link: '/examples/' }
],
sidebar: {
'/guide/': [
{
text: '介绍',
items: [
{ text: '开始使用', link: '/guide/' },
{ text: '安装', link: '/guide/installation' },
{ text: '配置', link: '/guide/configuration' }
]
},
{
text: '核心概念',
items: [
{ text: '身份验证', link: '/guide/auth' },
{ text: '数据获取', link: '/guide/fetching' }
]
}
]
},
socialLinks: [
{ icon: 'github', link: 'https://github.com/user/repo' }
]
}
});
2. Docusaurus(基于React)
// docusaurus.config.js
module.exports = {
title: '我的库',
tagline: '一个现代TypeScript库',
url: 'https://mylib.dev',
baseUrl: '/',
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
sidebarPath: require.resolve('./sidebars.js'),
editUrl: 'https://github.com/user/repo/edit/main/',
},
blog: {
showReadingTime: true,
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
themeConfig: {
navbar: {
title: '我的库',
items: [
{ to: '/docs/intro', label: '文档', position: 'left' },
{ to: '/blog', label: '博客', position: 'left' },
{
href: 'https://github.com/user/repo',
label: 'GitHub',
position: 'right',
},
],
},
},
};
自动化检查
1. 链接检查
# .github/workflows/docs.yml
name: 检查文档
on: [push, pull_request]
jobs:
check-links:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 检查损坏链接
uses: gaurav-nelson/github-action-markdown-link-check@v1
with:
folder-path: 'docs/'
config-file: '.markdown-link-check.json'
2. 代码示例测试
// 从Markdown提取并测试代码示例
import { readFileSync } from 'fs';
describe('文档示例', () => {
it('README示例工作', () => {
const readme = readFileSync('README.md', 'utf-8');
const codeBlocks = readme.match(/```typescript
([\s\S]*?)```/g);
// 测试每个代码块
for (const block of codeBlocks) {
const code = block.replace(/```typescript
/, '').replace(/```$/, '');
expect(() => eval(code)).not.toThrow();
}
});
});
文档清单
必备文档:
□ 带有快速开始的README.md
□ 带有版本的CHANGELOG.md
□ 许可证文件
□ 给贡献者的CONTRIBUTING.md
□ API参考文档
□ 配置指南
代码文档:
□ 公共API的JSDoc注释
□ 导出的类型定义
□ 复杂函数的示例
□ 错误条件文档化
□ 破坏性变更记录
质量:
□ 无损坏链接
□ 代码示例经过测试
□ 截图保持更新
□ 搜索功能
□ 移动端响应式
□ 可访问性(WCAG)
维护:
□ 从代码自动生成
□ 版本化文档
□ CI/CD文档检查
□ 弃用警告可见
□ 破坏性变更的迁移指南
资源
记住:文档是产品的一部分。保持准确、可访问和最新。