Skip to content

使用 Redocly CLI 生成漂亮的API文档

Redocly CLI 是目前最专业的 OpenAPI 文档生成工具,可以创建美观、交互式的 API 文档。

🎯 功能特点

  • 美观界面 - 现代化设计,响应式布局
  • 交互功能 - 在线测试 API,实时代码示例
  • 高度定制 - 丰富的主题选项和样式配置
  • 多种部署 - 支持静态文件、Docker、CDN 等部署方式
  • 实时预览 - 开发时实时预览效果

🚀 快速开始

安装

bash
npm install -g @redocly/cli

基本命令

bash
# 生成 HTML 文档
npx @redocly/cli build-docs api.yaml -o docs.html

# 启动预览服务器
npx @redocly/cli preview-docs api.yaml

# 指定端口
npx @redocly/cli preview-docs api.yaml --port 3000

📚 生成选项

基本配置

bash
npx @redocly/cli build-docs api.yaml -o docs.html
bash
npx @redocly/cli build-docs api.yaml \
  --title="我的 API 文档" \
  -o docs.html
bash
npx @redocly/cli build-docs api.yaml \
  --disableGoogleFont \
  -o docs.html

主题选项

bash
# 配置主题选项
npx @redocly/cli build-docs api.yaml \
  --title="Team Smart API" \
  --theme.openapi.hideDownloadButton=false \
  --theme.openapi.disableSearch=false \
  --theme.openapi.pathInMiddlePanel=true \
  -o docs.html

支持的主题参数

参数类型默认值说明
hideDownloadButtonbooleanfalse隐藏下载按钮
disableSearchbooleanfalse禁用搜索功能
pathInMiddlePanelbooleanfalse路径显示在中间面板
hideRequestPayloadSamplebooleanfalse隐藏请求示例
hideResponsePayloadSamplebooleanfalse隐藏响应示例
requiredPropsFirstbooleantrue必需属性优先显示
sortPropsAlphabeticallybooleanfalse属性按字母排序
showExtensionsbooleantrue显示扩展字段
nativeScrollbarsbooleanfalse使用原生滚动条

🎨 不同风格示例

简洁风格

bash
npx @redocly/cli build-docs api.yaml \
  --title="简洁 API 文档" \
  --theme.openapi.hideDownloadButton=true \
  --theme.openapi.disableSearch=false \
  --theme.openapi.pathInMiddlePanel=true \
  -o docs/clean.html

开发者友好风格

bash
npx @redocly/cli build-docs api.yaml \
  --title="开发者 API 指南" \
  --theme.openapi.hideDownloadButton=false \
  --theme.openapi.showExtensions=true \
  --theme.openapi.requiredPropsFirst=true \
  -o docs/developer.html

企业级风格

bash
npx @redocly/cli build-docs api.yaml \
  --title="企业 API 文档" \
  --theme.openapi.sortPropsAlphabetically=true \
  --theme.openapi.pathInMiddlePanel=false \
  --disableGoogleFont=true \
  -o docs/enterprise.html

⚙️ 配置文件方式

基础配置

创建 redocly.yaml

yaml
extends:
  - recommended

apis:
  main:
    root: api/openapi.yaml

theme:
  openapi:
    disableSearch: false
    hideDownloadButton: false
    pathInMiddlePanel: true
    requiredPropsFirst: true
    showExtensions: true

rules:
  security-defined: off
  no-unresolved-refs: error
  operation-summary: error

使用配置文件

bash
npx @redocly/cli build-docs --config redocly.yaml -o docs.html

高级配置示例

yaml
extends:
  - recommended

apis:
  main:
    root: api/openapi-bundled.yaml

theme:
  openapi:
    # 布局设置
    disableSearch: false
    hideDownloadButton: false
    pathInMiddlePanel: true
    
    # 内容设置
    hideRequestPayloadSample: false
    hideResponsePayloadSample: false
    requiredPropsFirst: true
    sortPropsAlphabetically: false
    showExtensions: true
    
    # 界面设置
    nativeScrollbars: false

rules:
  # 关闭安全警告
  security-defined: off
  # 严格检查
  no-unresolved-refs: error
  no-unused-components: warn
  # 操作要求
  operation-summary: error
  operation-description: warn
  operation-operationId: error
  operation-tag-defined: error

🎭 自定义主题

CSS 样式定制

虽然 Redocly CLI 不直接支持 CSS 注入,但可以通过后处理修改生成的 HTML:

javascript
// post-process.js
import fs from 'fs';

const customCSS = `
<style>
/* 自定义样式 */
.api-info-wrapper h1 {
  background: linear-gradient(135deg, #1976d2, #42a5f5);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.operation-type.get { background-color: #4caf50; }
.operation-type.post { background-color: #2196f3; }
.operation-type.put { background-color: #ff9800; }
.operation-type.delete { background-color: #f44336; }

/* 代码块美化 */
pre {
  background-color: #2d3748 !important;
  border-radius: 8px;
}
</style>
`;

function addCustomStyles(htmlFile) {
  let content = fs.readFileSync(htmlFile, 'utf8');
  content = content.replace('</head>', `${customCSS}</head>`);
  fs.writeFileSync(htmlFile, content);
}

// 使用
addCustomStyles('docs.html');

自定义模板

对于高度定制,可以使用自定义 Handlebars 模板:

bash
npx @redocly/cli build-docs api.yaml \
  --template=custom-template.hbs \
  --templateOptions.metaDescription="我的 API 文档" \
  -o docs.html

🚀 批量生成脚本

创建 generate-docs.sh

bash
#!/bin/bash

echo "📚 Generating API Documentation..."

# 创建输出目录
mkdir -p docs

# 合并 OpenAPI 文件
echo "📦 Bundling OpenAPI files..."
npx @redocly/cli bundle api/openapi.yaml -o api/openapi-bundled.yaml

# 生成不同风格的文档
echo "🎨 Generating different documentation styles..."

# 完整文档
npx @redocly/cli build-docs api/openapi-bundled.yaml \
  --title="Complete API Documentation" \
  --theme.openapi.hideDownloadButton=false \
  --theme.openapi.disableSearch=false \
  -o docs/complete.html

# 快速参考
npx @redocly/cli build-docs api/openapi-bundled.yaml \
  --title="Quick API Reference" \
  --theme.openapi.hideDownloadButton=true \
  --theme.openapi.pathInMiddlePanel=true \
  -o docs/quick-reference.html

# 开发者指南
npx @redocly/cli build-docs api/openapi-bundled.yaml \
  --title="Developer API Guide" \
  --theme.openapi.showExtensions=true \
  --theme.openapi.requiredPropsFirst=true \
  -o docs/developer-guide.html

# 创建主页
cp docs/complete.html docs/index.html

echo "✨ Documentation generated successfully!"
echo "📁 Files:"
echo "   - docs/index.html (Main)"
echo "   - docs/complete.html (Complete)"
echo "   - docs/quick-reference.html (Quick reference)"
echo "   - docs/developer-guide.html (Developer guide)"

Windows 批处理版本

创建 generate-docs.bat

batch
@echo off
echo 📚 Generating API Documentation...

if not exist "docs" mkdir docs

echo 📦 Bundling OpenAPI files...
npx @redocly/cli bundle api/openapi.yaml -o api/openapi-bundled.yaml

echo 🎨 Generating different documentation styles...

REM 完整文档
npx @redocly/cli build-docs api/openapi-bundled.yaml --title="Complete API Documentation" --theme.openapi.hideDownloadButton=false --theme.openapi.disableSearch=false -o docs/complete.html

REM 快速参考
npx @redocly/cli build-docs api/openapi-bundled.yaml --title="Quick API Reference" --theme.openapi.hideDownloadButton=true --theme.openapi.pathInMiddlePanel=true -o docs/quick-reference.html

REM 开发者指南
npx @redocly/cli build-docs api/openapi-bundled.yaml --title="Developer API Guide" --theme.openapi.showExtensions=true --theme.openapi.requiredPropsFirst=true -o docs/developer-guide.html

copy docs\\complete.html docs\\index.html

echo ✨ Documentation generated successfully!

🌐 部署方案

静态文件部署

生成的 HTML 文件是自包含的,可以直接部署:

bash
# 部署到任何静态服务器
cp docs/index.html /var/www/html/api-docs.html

# 或使用 Node.js 服务器
npx serve docs -p 3000

GitHub Pages

yaml
# .github/workflows/docs.yml
name: Deploy API Docs

on:
  push:
    branches: [main]
    paths: ['api/**']

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          
      - name: Install Redocly CLI
        run: npm install -g @redocly/cli
        
      - name: Generate Documentation
        run: |
          npx @redocly/cli bundle api/openapi.yaml -o api/openapi-bundled.yaml
          npx @redocly/cli build-docs api/openapi-bundled.yaml \
            --title="API Documentation" \
            -o docs/index.html
            
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs

Docker 部署

创建 Dockerfile

dockerfile
FROM nginx:alpine

# 复制文档
COPY docs/ /usr/share/nginx/html/

# 自定义 Nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

创建 nginx.conf

nginx
server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;
    index index.html;

    # 缓存静态资源
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    
    # 文档页面
    location / {
        try_files $uri $uri/ =404;
        add_header Cache-Control "public, max-age=3600";
    }
}

部署:

bash
docker build -t api-docs .
docker run -p 8080:80 api-docs

CDN 部署

bash
# 部署到 AWS S3 + CloudFront
aws s3 sync docs/ s3://my-api-docs-bucket/
aws cloudfront create-invalidation --distribution-id E123456789 --paths "/*"

# 部署到 Netlify
netlify deploy --prod --dir=docs

# 部署到 Vercel
vercel --prod docs/

📊 实时预览

开发服务器

bash
# 启动预览服务器
npx @redocly/cli preview-docs api/openapi.yaml

# 指定端口和主机
npx @redocly/cli preview-docs api/openapi.yaml --host 0.0.0.0 --port 8080

# 使用配置文件
npx @redocly/cli preview-docs --config redocly.yaml

监听文件变化

预览服务器会自动监听文件变化并刷新页面,非常适合开发阶段使用。

🔍 质量检查

文档验证

bash
# 验证 OpenAPI 规范
npx @redocly/cli lint api/openapi.yaml

# 获取统计信息
npx @redocly/cli stats api/openapi.yaml

# 检查生成的文档大小
ls -lh docs/*.html

性能优化

bash
# 移除未使用的组件以减小文件大小
npx @redocly/cli bundle api/openapi.yaml \
  --remove-unused-components \
  -o api/openapi-optimized.yaml

npx @redocly/cli build-docs api/openapi-optimized.yaml \
  -o docs/optimized.html

⚠️ 常见问题

1. 安全方案警告

Non existing security scheme referenced: bearerAuth

解决方案:在配置文件中关闭安全检查

yaml
rules:
  security-defined: off

2. 文件过大

问题:生成的 HTML 文件过大 解决方案

  • 移除未使用的组件
  • 优化 OpenAPI 规范
  • 分割大型 API 文档

3. 中文显示问题

解决方案:确保 OpenAPI 文件使用 UTF-8 编码

bash
file -bi api/openapi.yaml

4. 自定义域名

部署到自定义域名时,确保正确配置:

bash
# 生成相对路径的文档
npx @redocly/cli build-docs api/openapi.yaml \
  --options.pathPrefix="/api-docs/" \
  -o docs/index.html

📝 最佳实践

1. 文档组织

project/
├── api/
│   ├── openapi.yaml
│   └── openapi-bundled.yaml
├── docs/
│   ├── index.html          # 主文档
│   ├── v1/                 # 版本化文档
│   └── internal/           # 内部文档
└── scripts/
    └── generate-docs.sh

2. 版本管理

bash
# 为不同版本生成文档
npx @redocly/cli build-docs api/v1/openapi.yaml -o docs/v1/index.html
npx @redocly/cli build-docs api/v2/openapi.yaml -o docs/v2/index.html
npx @redocly/cli build-docs api/v3/openapi.yaml -o docs/v3/index.html

3. 自动化集成

  • 在 CI/CD 中自动生成文档
  • 合并代码时自动更新文档
  • 定期检查文档质量

4. 性能优化

  • 合并前移除未使用组件
  • 使用 CDN 加速文档访问
  • 启用 gzip 压缩

通过 Redocly CLI,你可以轻松生成专业级的 API 文档,提升开发体验和 API 可用性。

SOLO Development Guide