Angular 工具篇之文档管理

  • 2019 年 11 月 6 日
  • 筆記

Angular 工具篇系列教程目录:

本文我们将介绍 Compodoc 这款工具,它用于为 Angular 应用程序生成静态文档。Compodoc 能够帮助 Angular开发人员为他们的应用程序生成清晰且有用的文档,这使得参与应用程序开发的其它成员也可以轻松了解当前应用程序或库的特性。

在安装 Compodoc 之前,我们先来简单了解一下它的特点:

  • 生成的文档结构清晰。
  • 支持多种主题风格,比如 laravel, original, material, postmark 等。
  • 支持快速检索,基于强大的 lunr.js 搜索引擎。
  • 支持 JSDoc 高亮,支持 @param, @returns, @link, @ignore@example 标签。
  • 支持文档覆盖率统计。
  • 对 Angular CLI 友好,支持 Angular CLI 创建的项目。
  • 离线化,无需服务器,不依赖线上资源,完全脱机生成的文档。

安装 compodoc

首先我们以 local 模式进行安装:

$ npm install --save-dev @compodoc/compodoc

当然你也可以选择 global 模式进行安装:

$ npm install -g @compodoc/compodoc

然后我们在项目的 package.json 中添加以下配置:

"scripts": {    "compodoc": "./node_modules/.bin/compodoc -p src/tsconfig.app.json"  }

配置完 npm script,我们就可以运行以下命令:

$ npm run compodoc

compodoc 命令支持很多选项,这里我们简单介绍几个比较常用的选项:

  1. -p, –tsconfig [config] —— 指定 tsconfig.json 文件的路径
  2. -n, –name [name] —— 文档的标题
  3. -s, –serve —— 启动本地文档服务器(默认地址为 http://localhost:8080/)
  4. -r, –port [port] —— 指定本地文档服务器的端口
  5. -w, –watch —— 启动监听模式,文件发生异动时自动编译
  6. –theme [theme] —— 设置主题风格,支持 laravel, original, material, postmark, readthedocs, stripe, vagrant。你可以访问 compodoc – themes 查看相关主题风格。
  7. -d, –output [folder] —— 指定文档的输出目录
  8. -h, –help —— 显示帮助信息

若需查看完整的配置项,可以浏览 compodoc – usage

文档注释

comments

Compodoc 使用 TypeScript AST 解析器和它的内部 API,因此注释必须是合法的 JSDoc 注释。

  1. 有效的注释
/**   * Supported comment   */
  1. 无效的注释
/*   * unsupported comment   */    /*    unsupported comment   */    // unsupported comment

通过观察上面的示例,我们可以得出一个结论,只有以 /** 开头的注释,才能被 compodoc 识别。

JSDoc Tags

由于 TypeScript 编译器的限制 目前 Compodoc 只支持以下的 JSDoc 标签:

  • @returns —— 描述返回值
  • @ignore —— 表示标记的内容永远不会出现在文档中
  • @param —— 定义一个参数的类型和描述
  • @link —— 定义链接另一个方法、文档或外部链接
  • @example —— 定义一个示例用法

了解完上述标签,我们来看一个比较完整的示例(来源于 ionic-code-documentation

import { Injectable } from '@angular/core';    /**    Provider for super difficult math operations  */  @Injectable()  export class MathProvider {      /**      Value of the last operation    */    storedValued: number;      /**     * @ignore     */    constructor() { }      /**     * Performs a very special operation     *     * @example     * Simply call it with 2 numbers:     * getResult(2, 3)     *     * @param {number} a First number     * @param {number} b Second number     * @returns The sum of a and b     */    getResult(a: number, b: number) : number {      let sum = a + b;      this.storedValued = sum;      return sum;    }  }

其实 Compodoc 除了能够根据 JSDoc 标签生成对应的文档之外,它还能为我们自动生成项目概况、路由信息、组件信息及文档覆盖率等。感兴趣的同学,可以访问线上的示例 compodoc-demo-todomvc-angular 详细了解情况。

总结

本文简单介绍了如何利用 Compodoc 这款工具,为 Angular 应用程序生成静态文档,Compodoc 基本上能够满足我们的需求。对 Angular 项目来说,除了 Compodoc 之外,你也可以考虑使用谷歌官方出品的 API 文档生成工具 Dgeni,它对外开放了丰富的接口,还支持插件扩展,具有非常强的定制性。