使用typeDoc快速生成开发文档

5,100 阅读3分钟

背景

部门 A 使用 ReactNative 开发,维护 RN 组件库,部门 B 使用原生开发,一天,为应付业务快速迭代,B 部门同学也需要接入 RN。于是就有了下面的问题

B 部门同学想要知道:

  • A 组件库支持什么功能
  • A 组件库的组件怎么使用

A 部门组件库存在的问题:

  • 没有文档说明(曾经有,迭代太快,写文档太麻烦,久而久之就过时了)
  • 注释较少,时间久了,原开发同学都离职了,想要搞清楚组件支持的功能得扒源码看

A同学需要经常支援B,比较麻烦,又不想花费太多时间去写文档。为了解决这个问题,参考原生开发使用过的 Java doc 工具,最后找到了这个--typedoc,使用下来体验还行,比每次扒源码方便,写篇文章分享一下这个工具

点击查看示例效果

TypeDoc 将 TypeScript 源代码中的注释转换为呈现的 HTML 文档或 JSON 模型。它是可扩展的,支持多种配置。

初始化工程

创建一个新的 TS React 应用来演示功能

npm install -g create-react-app
create-react-app type-doc-demo --template typescript

安装typeDoc

npm install typedoc --save-dev

工程说明

组件工程的目录结构如下所示

.
├── components
│   ├── Card
│   │   └── index.tsx
│   ├── Filter
│   │   └── index.tsx
│   └── index.tsx
├── demo
│   └── Filter.tsx
├── App.tsx
...

components/index.tsx导出所有组件,demo目录包含示例代码。

// components/index.tsx
export { Card } from "./Card";
export type { CardProps } from "./Card";
export { Filter } from "./Filter";
export type { FilterProps } from "./Filter";

基础功能

在项目根目录创建typedoc.js文件,指定入口文件和输出目录

// typedoc.js
module.exports = {
  entryPoints: ["./src/components/index.tsx"],
  out: "doc",
  name: "组件库",
};

package.json添加脚本打包看看效果

// package.json
...
 "scripts": {
    "doc": "typedoc --tsconfig tsconfig.json --options typedoc.js"
  },
...

执行 npm run doc,效果如下,默认会将README.md内容放在首页

image.png

MarkDown语法

typeDoc将通过导出内容的注释生成文档,注释支持MarkDown语法,所以可以将注释这么写

  • 插入表格
export type FilterProps = {
    /**
   * 弹窗类型
   *
   * |drop|fullscreen|
   * |:---:|:---:|
   * |下拉| 全屏|
   *  */
  modalMode?: "dorp" | "fullscreen";
};
  • 插入示例代码
export type FilterProps = {
  /**
   * 配置
   * ```
   * {
   *        base_filter: {
   *          checkBox: {
   *            columns: 4,
   *          },
   *        },
   *      }
   *```
   */
  config?: object;
};

生成文档效果

image.png

插入自定义资源

typedoc.js增加如下配置

// typedoc.js
module.exports = {
  ...
  media: ["./demo-images"],
  includes: ["./src/demo"],
};

  • includes: 包含文件的目录,这些文件可以[[include:file.md]]在文档注释中注入到生成的文档中。
  • media:指定将复制到输出文件的媒体目录。媒体可以media://file.jpg在文档注释中链接到

添加上述配置后,在注释中就可以通过如下方式访问对应资源了

/**
 * # 筛选器
 * ## 示例图
 * <img src="media://Filter.jpg"  width="50%" />
 *
 * @see [数据格式说明文档](https://www.baidu.com)
 *
 * ## 代码示例
 * ### 使用
 * ```
 * [[include:Filter.tsx]]
 * ```
 **/
export const Filter: React.FC<FilterProps> = () => {
  ...
};

生成文档效果如下

image.png

综上,便以较小的工作量生成了一个简单的开发文档,提供了代码示例、功能示例图、属性说明,如果只供内部使用的话还比较方便。

其他配置

配置文件

可以再typedoc.js文件中填下如下配置

module.exports = {
  excludePrivate: true,  // 导出不包含private声明内容
  excludeProtected: true, // 导出不包含protected声明内容
  // 将包版本添加到项目名称中。在这种情况下,如果项目是根据 1.2.3 版本`package.json`,这将生成名为“名称 - v1.2.3”的文档
  includeVersion: true, 
};

注释标签

  • @ignore: 文档忽略该模块
  • @category: 将该内容分组,同标签会划分一起

image.png

相关链接