注释写的好,文档不潦草.

news2025/7/13 10:06:39

大家好,long time no see!这次聊一聊「注释」。写「注释」的好处众所周知,但有时在实现一些「公共代码」后,需要编写「文档」,其中「注释」和「文档」的内容是大致相同的,比如paramreturns等(相信有不少同学试过把「注释」copy到「文档」中吧🌝)。So,有没有一种可能,直接把「注释」直接转化为「文档」呢?

背景

👨‍💼:一会抽空优化下JsBridge,写好注释!写好文档!

JsBridge:用于「Hybrid」开发模式下,「Native 原生」和「Web H5」之间通信。

🧑‍💻:JsBridge里面几十个方法,写完注释还要写文档,得花不少时间。

👨‍💼:你傻啊,不会用TypeDoc吗?

🧑‍💻:就是那个根据「代码」直接生成「文档」的工具吗?我这就去试试!

TypeDoc

TypeScript的「文档生成器」,通过读取TypeScript源文件,解析其中包含的注释,并为代码生成包含文档的「静态站点」。

安装

$ npm install typedoc --save-dev
复制代码

安装时,要注意对应项目的typescript版本

TypeDoc VersionTypeScript Version(s)
0.234.6 through 4.8
0.224.0 through 4.7
0.214.0 through 4.4
0.203.9 through 4.2
0.193.9 through 4.0

使用方式

TypeDoc提供两种了运行方式:

  • Cli
  • Node Module

Cli

使用「命令行」运行时,有三种配置方式:

  1. 把所有参数添加在「命令」中:
$ typedoc --out docs src/index.ts
复制代码
  1. 使用typedoc.json(推荐):

在项目的「根路径」下创建typedoc.json

./typedoc.json

{
    "entryPoints": ["src/index.ts"],
    "out": "docs"
}
复制代码
  1. tsconfig.json中配置:

tsconfig.json中的typedocOptions字段定义参数。

{
    // ...
    "typedocOptions": {
        "entryPoints": ["src/index.ts"],
        "out": "docs"
    }
}
复制代码

Node Module

如果想要「动态配置」或者不使用Cli来运行typedoc,可以require("typedoc")进行文档构建。

const TypeDoc = require("typedoc")

// 初始化
const app = new TypeDoc.Application()
// 读取 tsconfig.json
app.options.addReader(new TypeDoc.TSConfigReader())
// or 读取 typedoc.json
app.options.addReader(new TypeDoc.TypeDocReader())
// or 直接配置
app.bootstrap({
   entryPoints: ["src/index.ts"],
});

const project = app.convert()
if (project) {
  const outputDir = "docs"
  // 生成文档
  await app.generateDocs(project, outputDir)
  // 生成json
  await app.generateJson(project, outputDir + "/documentation.json")
}
复制代码

具体的参数配置,👉 传送门

插件

使用plugin字段扩展TypeDoc的能力。

{
  // ...
  plugin: ['typedoc-plugin-markdown'],
}
复制代码

默认情况下,TypeDoc只生成html的静态站点文档,如需Markdown格式,可添加typedoc-plugin-markdown,生成对应的Markdown文档。

更多的官方插件,👉 传送门

Tips: 在npm的typedoc-plugin关键字下可以找到更多插件。

主题

使用theme字段配置生成文档的主题。

{
  // ...
  "plugin": ["typedoc-theme-hierarchy"],
  "theme": "hierarchy",
}
复制代码

使用主题时,要先添加进plugin中,再添加到theme中。

更多主题,👉 传送门

Tips: 在npm的typedoc-theme关键字下可以找到更多主题。

TSDoc

TypeDoc不是万能的,“龙飞凤舞”的「注释」生成不了「文档」,或者生成后的「文档」阅读性很差。

因此,这就要求我们✍️「注释」时要符合“规范”!

没错,用别人的工具,就要遵守别人的规则,这个“规范”就是TSDoc

TSDoc是标准化TypeScript代码中使用的文档注释,这样不同的工具就可以提取内容,而不会被彼此的标记混淆。

通俗来说,TSDoc就是「微软」的一套「注释规范」,主要用于统一某些工具(除了TypeDoc外还有DocFX、API Extractor等)对「注释」的识别,避免每个工具都搞一套自己的注释规范。

Tags(重点)

正确使用Tags是写好注释的基础。

标签名以 @ 开头,后面跟着使用「驼峰大小写的ASCII字母」。

kind

Tags根据「类型」来区分,分三种:

  • Block tags
  • Modifier tags
  • Inline tags

Block tags

「块级」标签:

  1. tags作为一行中「第一个」出现的元素;
  2. 一行中仅允许该tags存在(很多Block tag都没遵守该约定);
  3. 直至遇到下个Block tags前,都是该tags的内容;
  4. 第一个Block tags前面的内容为“摘要”;

Modifier tags

「修饰」标签:

  1. 内容为空的Block tags
  2. 出现在注释底部;

Inline tags

「行内」标签:

  1. Markdown表达式一起作为内容元素出现;
  2. 被 { } 字符包围;

Standardization

Tags根据「兼容性」来区分,分三组:

  • Core
  • Extended
  • Discretionary

Core

每个「文档工具」都支持。

Extended

「文档工具」可能支持,也可能不支持,需要查阅该工具的文档。

Discretionary

针对某个/些「文档工具」而自身定制的tags

常用的Tags

@alpha

表示该Api的发布阶段为alpha

Standardizationkind
DiscretionaryModifier
export class Book {
  /**
   * The title of the book.
   * @alpha
   */
  public get title(): string;
};
复制代码

@beta @experimental

beta与experimental同义

表示该Api的发布阶段为beta/experimental

Standardizationkind
DiscretionaryModifier
export class Book {
  /**
   * The title of the book.
   * @beta
   */
  public get title(): string;
};
复制代码

@internal

表示该Api不计划供第三方使用。

Standardizationkind
DiscretionaryModifier
export class Book {
  /**
   * The title of the book.
   * @internal
   */
  public get _title(): string;
};
复制代码

@public

表示该Api的发布阶段为public,代表已正式发布且稳定的(可省略)。

Standardizationkind
DiscretionaryModifier
export class Book {
  public get title(): string;
};
复制代码

@decorator

由于TypeScript编译器并不能识别.d.ts中的「装饰器」,所以使用该tag在文档注释中引用decorator表达式。

Standardizationkind
ExtendedBlock
class Book {
  /**
   * The title of the book.
   * @decorator `@jsonSerialized`
   * @decorator `@jsonFormat(JsonFormats.Url)`
   */
  @jsonSerialized
  @jsonFormat(JsonFormats.Url)
  public website: string;
}
复制代码

@deprecated

表示该Api不再被支持,未来可能会被删除,其后面是替代方案。

Standardizationkind
CoreBlock
/**
 * The base class for controls that can be rendered.
 *
 * @deprecated Use the new {@link Control} base class instead.
 */
export class VisualControl {
  . . .
}
复制代码

@defaultValue

如果未显式分配值,则用于记录字段或属性的默认值。

⚠️:该标记只能用于作为类或接口成员的字段或属性。

Standardizationkind
ExtendedBlock
enum WarningStyle {
  DialogBox,
  StatusMessage,
  LogOnly
}

interface IWarningOptions {
  /**
   * Determines how the warning will be displayed.
   *
   * @defaultValue `WarningStyle.DialogBox`
   */
  warningStyle: WarningStyle;
}
复制代码

@eventProperty

应用于「类」或者「接口属性」时,表示其返回的「事件处理程序」可以附加到事件对象上(通常具备addHandler()removeHandler())。

⚠️:「文档工具」会把该类/属性归纳到「事件」内。

Standardizationkind
ExtendedModifier
class MyClass {
  /**
    * This event is fired whenever the application navigates to a new page.
    * @eventProperty
    */
  public readonly navigatedEvent: FrameworkEvent<NavigatedEventArgs>;
}
复制代码

@example

演示如何使用该Api,可能包含一个代码示例。

与该tag出现在同一行上的后续文本为示例的标题。

Standardizationkind
ExtendedBlock
/**
 * Adds two numbers together.
 * @example
 * Here's a simple example:
 * ```
 * // Prints "2":
 * console.log(add(1,1));
 * ```
 */
export function add(x: number, y: number): number {
}
复制代码

@inheritDoc

用于复制另一个Apitag,甚至可以从一个不相关的package中进行复制。

⚠️:并不是所有的tags都能被复制,只有remarksparamstypeParamreturns能被复制。

Standardizationkind
ExtendedInline
import { Serializer } from 'example-library';

export interface IWidget {
  /**
   * Draws the widget on the display surface.
   * @param x - the X position of the widget
   * @param y - the Y position of the widget
   */
  public draw(x: number, y: number): void;
}

export class Button implements IWidget {
  /** {@inheritDoc IWidget.draw} */
  public draw(x: number, y: number): void {
    . . .
  }

  /**
   * {@inheritDoc example-library#Serializer.writeFile}
   */
  public save(): void {
    . . .
  }
}
复制代码

@label

表示一个声明,可在TSDoc中使用「选择器」引用它。

⚠️:该tag还没有最终确定。👉 GitHub issue #9

Standardizationkind
CoreInline
export interface Interface {
  /**
   * Shortest name:  {@link InterfaceL1.(:STRING_INDEXER)}
   * Full name:      {@link (InterfaceL1:interface).(:STRING_INDEXER)}
   *
   * {@label STRING_INDEXER}
   */
  [key: string]: number;

  /**
   * Shortest name:  {@link InterfaceL1.(:CONSTRUCTOR)}
   * Full name:      {@link (InterfaceL1:interface).(:CONSTRUCTOR)}
   *
   * {@label CONSTRUCTOR}
   */
  new (hour: number, minute: number);
}
复制代码

@link

表示用于创建到文档系统中其他页面或一般的url超链接。

⚠️:该tag还没有最终确定。👉 GitHub issue #9

Standardizationkind
CoreInline
/**
 * Links can point to a URL: {@link https://github.com/microsoft/tsdoc}
 */
复制代码

@override @sealed @virtual

  • @override: 表示此定义覆盖父类的定义;
  • @sealed: 表示该定义不能被继承,且不得被重写;
  • @virtual:表示该定义能被继承,能被重写;

⚠️:「文档工具」强制要求virtualoverridesealed同时使用。

Standardizationkind
ExtendedModifier
class Base {
  /** @virtual */
  public render(): void {
  }

  /** @sealed */
  public initialize(): void {
  }
}

class Child extends Base {
  /** @override */
  public render(): void;
}
复制代码

@packageDocumentation

表示描述整个package的文档注释。

⚠️:注释在.d.ts文件中,且不得用于描述单项Api

Standardizationkind
CoreModifier
// Copyright (c) Example Company. All rights reserved. Licensed under the MIT license.

/**
 * A library for building widgets.
 *
 * @remarks
 * The `widget-lib` defines the {@link IWidget} interface and {@link Widget} class,
 * which are used to build widgets.
 *
 * @packageDocumentation
 */

/**
 * Interface implemented by all widgets.
 * @public
 */
export interface IWidget {
  /**
   * Draws the widget on the screen.
   */
  render(): void;
}
复制代码

@param

用于记录函数参数,后面是一个参数名,后面是一个连字符,最后是一个描述。

Standardizationkind
CoreBlock
/**
 * @param x - The first input number
 * @param y - The second input number
 */
function getAverage(x: number, y: number): number {
  return (x + y) / 2.0;
}
复制代码

@returns

用于记录函数的返回值。

Standardizationkind
CoreBlock
/**
 * @returns The arithmetic mean of `x` and `y`
 */
function getAverage(x: number, y: number): number {
  return (x + y) / 2.0;
}
复制代码

@remarks @privateRemarks

  • @remarks:表示一个简短的公开的“摘要”;
  • @privateRemarks:表示一个简短的非公开的“摘要”;
Standardizationkind
CoreBlock
/**
 * @remarks
 *
 * The main documentation for an API item is separated into a brief
 * "summary" section optionally followed by an `@remarks` block containing
 * additional details.
 *
 * @privateRemarks
 *
 * The `@privateRemarks` tag starts a block of additional commentary that is not meant
 * for an external audience.  A documentation tool must omit this content from an
 * API reference web site.  It should also be omitted when generating a normalized
 * *.d.ts file.
 */
复制代码

@readonly

表示「只读」属性。

Standardizationkind
ExtendedModifier
export class Book {
  /**
   * Technically property has a setter, but for documentation purposes it should
   * be presented as readonly.
   * @readonly
   */
  public get title(): string {
    return this._title;
  }

  public set title(value: string) {
    throw new Error('This property is read-only!');
  }
}
复制代码

@see

表示与当前Api相关的其他资源的引用列表。

⚠️:JSDocsee之后立即生成超链接文本。但TSDoc需要显式的link来生成超链接。

Standardizationkind
ExtendedBlock
/**
 * Parses a string containing a Uniform Resource Locator (URL).
 * @see {@link ParsedUrl} for the returned data structure
 * @see {@link https://tools.ietf.org/html/rfc1738|RFC 1738}
 * for syntax
 * @see your developer SDK for code samples
 * @param url - the string to be parsed
 * @returns the parsed result
 */
function parseURL(url: string): ParsedUrl;
复制代码

@throws

表示可能由「函数」或「属性」引发的异常类型。

⚠️:每种异常类型都应该单独使用一个throw进行描述。

Standardizationkind
ExtendedBlock
/**
 * Retrieves metadata about a book from the catalog.
 *
 * @param isbnCode - the ISBN number for the book
 * @returns the retrieved book object
 *
 * @throws {@link IsbnSyntaxError}
 * This exception is thrown if the input is not a valid ISBN number.
 *
 * @throws {@link book-lib#BookNotFoundError}
 * Thrown if the ISBN number is valid, but no such book exists in the catalog.
 *
 * @public
 */
function fetchBookByIsbn(isbnCode: string): Book;
复制代码

@typeParam

用于记录通用参数,后面是一个参数名,后面是一个连字符,最后是一个描述。

Standardizationkind
CoreBlock
/**
 * Alias for array
 *
 * @typeParam T - Type of objects the list contains
 */
type List<T> = Array<T>;

/**
 * Wrapper for an HTTP Response
 * @typeParam B - Response body
 * @param <H> - Headers
 */
interface HttpResponse<B, H> {
    body: B;
    headers: H;
    statusCode: number;
}
复制代码

最后

👨‍💼:不错不错,文档写的很好!顺便把以前的文档都重写一遍吧!

🧑‍💻:卒。

参考文章:

  • TSDoc
  • TypeDoc

祝大家生活愉快,工作顺利!

「 ---------- The end ---------- 」

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/18026.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java_抽象类和接口(一)

作者&#xff1a;爱塔居的博客_CSDN博客-JavaSE领域博主 专栏&#xff1a;JavaSE 作者简介&#xff1a;大三学生&#xff0c;希望跟大家一起进步&#xff01; 文章目录 目录 文章目录 一、抽象类 1.1 抽象类概念 1.2 抽象类语句 1.3 抽象类特性 1.4 抽象类和普通类的区别 1.5 抽…

赞不绝口!仅靠阿里P9分享的 Redis 工作手册,拿到60W年薪Offer

昨晚有六七位小伙伴告诉我说&#xff1a;“大佬&#xff0c;有没有Redis的面试教程啊&#xff0c;最近面试被问到好多” 这就帮小伙伴们专门整理了一份资料&#xff08;不仅仅是面试题&#xff09;&#xff0c;从Redis核心原理到Redis设计与源码帮助大家梳理体系&#xff0c;快…

教你自己写Arcpy批处理程序

自己写Arcpy批处理栅格和矢量 先上代码&#xff0c;讲解各行代码的意思&#xff0c;从而达到自己写代码的目的 #....Edit by Longhao Wang.... import arcpy from arcpy import env from arcpy.sa import * import os import os.path import sys arcpy.env.workspace"D:…

Vue项目开发经验

文章目录前言网页组件echarts使用打包后显示包体积安装tensorflow和anaconda可能出现的错误![在这里插入图片描述](https://img-blog.csdnimg.cn/c1facd95a7f645c5af3e8dc1237913a3.png)总结前言 本博客仅做学习笔记&#xff0c;如有侵权&#xff0c;联系后即刻更改 科普&…

《调试九法》阅读笔记

1. 理解系统 阅读手册、仔细阅读每个细节、掌握基础知识、了解工作流程、了解工具。 2. 制造失败 制造失败、从头开始、引发失败、但不要模拟失败、查找不受你控制的条件、记录每件事情&#xff0c;并找到间歇性bug特征、不要过于相信统计数据、要认识到“那”是可能会发生的…

[附源码]java毕业设计商场日常维修管理系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

【云原生】k8s 中的 hostNetwork 和 NetworkPolicy(网络策略)讲解与实战操作

文章目录一、hostNetwork 介绍二、k8s 网络策略 NetworkPolicy三、Pod 隔离的两种类型四、NetworkPolicy 资源1&#xff09;NetworkPolicy 示例演示2&#xff09;选择器 to 和 from 的行为五、总结一、hostNetwork 介绍 在k8s中&#xff0c;若pod使用主机网络&#xff0c;也就是…

UE5笔记【四】UE5主材质Master Materials和材质实例MI

上一篇我们讲解了关于鹅卵石的纹理材质。 假设&#xff1a;如果我们在关卡中每个材质都这么连接的话&#xff0c;那么将使得整个世界非常复杂&#xff0c;并且将浪费大量的时间。对此&#xff0c;解决方案是&#xff1a;主材质&#xff1a;master Materials。 新建一个新关卡…

springboot基于java的个性化推荐的电商购物商城平台设计与实现

本文主要探讨了个性化推荐的电商平台的设计与实现。并对其详细的设计方案、实现技术和运行情况做了分析和研究&#xff0c;最后对未来的工作做了研究与探讨。本文重点研究了以下几个方面&#xff1a; &#xff08;1&#xff09;系统的体系结构、主要功能模块、主要数据的工作流…

次元裂缝已打开,AI绘画突飞猛进,其潜力究竟有多大

目录 次元裂缝已打开 AI绘画 起源 人工智能画的画在美术比赛得第一名 原理 关键的CLIP 总结 次元裂缝已打开 #次元裂缝已打开#的一个话题火了~大量新人老玩家共赴无界AI 上面是AI绘画根据真实图片合成的图片与真图的对比&#xff0c;可以看出还原度还是很高的&#xff…

JUC学习笔记——共享模型之无锁

在本系列内容中我们会对JUC做一个系统的学习&#xff0c;本片将会介绍JUC的无锁 我们会分为以下几部分进行介绍&#xff1a; 无锁操作CAS与Volatile原子类型原理篇Unsafe 并发无锁操作 这一小节我们将讲解如何用无锁操作完成并发操作 问题展现 我们给出一段之前并发展示代…

机器人学优质资源

引言 实验室闲着查资料&#xff0c;发现西北大学有个很好的机器人学线上资源课程&#xff0c;Coursera上也有&#xff0c;记录一下&#xff0c;感觉还挺全的&#xff0c;而且GitHub上也开放了很多相应的学习资源。 Coursera的视频&#xff1a; Modern Robotics: Mechanics, Pla…

GitHub标星75k,阿里15W字的Spring高级文档(全彩版),真的太香了

随着 Spring 使用越来越广泛&#xff0c;Spring 已经成为 Java 程序员面试的必问知识点&#xff0c;很多同学对于Spring理解不是那么的深刻&#xff0c;经常就会被几个连环追问给干趴了&#xff01; 今天小编整理了一下一线架构师的Spring源码高级文档&#xff1a;SpringSprin…

Java三大特征之一——继承

继承继承概述、使用继承的好处继承得儿设计规范&#xff0c;内存运行原理继承的特点继承后&#xff1a;成员变量、成员方法的访问特点继承后&#xff1a;方法重写继承后&#xff1a;子类构造器的特点继承后&#xff1a;子类构造器访问父类有参数构造器this、super总结继承概述、…

挂耳耳机十大品牌排行榜哪个好,目前排行靠前的五款耳机推荐

耳机作为生活的必需品&#xff0c;随着我们生活水平的提高&#xff0c;对于耳机的需求也随之加强&#xff0c;既需要在运动中使用&#xff0c;又要能够在日常佩戴照常无误&#xff0c;那么在此我的建议是对于防水性能一定要高&#xff0c;毕竟高的防水能够抵挡运动中的汗水&…

WPF MVVM

WPF MVVM MVVMModelViewViewModel Model:现实世界中对象抽象的结果&#xff0c;也就是实体模型View:UI界面ViewModel:为UI界面服务的模型&#xff0c;可以理解为数据传输对象&#xff08;DTO&#xff09; ViewModel和View的沟通有两个方面&#xff1a;数据和操作传递数据–使…

“综合”web项目编写------手把手0基础教学(二)

上一节介绍了编写综合项目的基本流程 “综合”web项目编写------手把手0基础教学&#xff08;一&#xff09; 这里将继续介绍项目的编写&#xff0c;一个一个功能挨个实现。 目录 实现用户的登录功能 一 . 编写工具包---封装数据库链接 二 . 构建数据模型 三 . 构建功能…

ASEMI代理艾赛斯IGBT管IXYB82N120C3H1

编辑-Z 艾赛斯IGBT管IXYB82N120C3H1参数&#xff1a; 型号&#xff1a;IXYB82N120C3H1 漏极-源极电压&#xff08;VCES&#xff09;&#xff1a;1200V 连续漏电流&#xff08;IC&#xff09;&#xff1a;82A 功耗&#xff08;PC&#xff09;&#xff1a;1040W 工作结温度…

spring cloud在bootstrap.properties配置spring.profiles.active无效

bootstrap.properties 配置 bootstrap.properties spring.profiles.activeprofiles.active bootstrap-dev.properties / bootstrap-test.properties #服务器地址 spring.cloud.nacos.config.server-addr127.0.0.1:8848 #项目的命名空间的ID spring.cloud.nacos.config.name…

m基于FPGA和MATLAB的数字CIC滤波器设计和实现

目录 1.算法概述 2.仿真效果预览 3.MATLAB/FPGA部分代码预览 4.完整MATLAB/FPGA程序 1.算法概述 CIC滤波器由一对或多对积分-梳状滤波器组成&#xff0c;在抽取CIC中&#xff0c;输入信号依次经过积分&#xff0c;降采样&#xff0c;以及与积分环节数目相同的梳状滤波器。在…