jsDoc是一个用于JavaScript的API文档生成器。它根据JavaScript文件中的注释信息,生成JS应用程序或模块的API文档。通过使用JSDoc标记如:命名空间,类,方法参数等,使开发者能够轻易地阅读代码,掌握代码定义的类和和其属性和方法,从而降低维护成本并提高开发效率。
JSDoc注释通常应该放在代码被记录之前。为了被JSDoc解析器识别,每个注释必须以 /** 序列开头,以便由JSDoc解析器识别
最简单的文档示例就是描述:
/** This is a description of the foo function. */
function foo() {
}
添加一个描述很简单–只需在文档注释中键入所需的说明。
可以使用特殊的 JSDoc标签 来提供更多信息。例如,如果函数是类的构造函数,则可以通过添加@constructor
标记来表示。
/**
* Represents a book.
* @constructor
*/
function Book(title, author) {
}
使用标签添加更多的信息。
/**
* Represents a book.
* @constructor
* @param {string} title - The title of the book.
* @param {string} author - The author of the book.
*/
function Book(title, author) {
}
一、常用注释规范
1.1 @constructor
构造函数声明注释
@constructor
明确一个构造函数
1.2 @param
参数注释
通过@param
来表示函数、类的方法的参数。@param是最常用的注释标签。参数标签可表示 一个参数的参数名、参数类型和参数描述的注释。通过参数注释,可以在vscode中联想出相应的参数类型,让开发更便捷。如:
/**
* 书本
* @constructor
* @param {string} title - 书名
* @param {string} author - 作者
*
*/
function Book(title,author){}
let book = new Book('hellow world','什么当当当啊?')
1.3@return
返回值注释
表示一个函数 的返回值,如果函数没有显示指定返回值可以不写。用法与@param
类似,区别在于return只有一个,所以不用指定参数名。
/**
* @return {Number} 返回值描述
*/
function test () { }
// 函数返回 Promise 实例的情况可以这么指定类型
/**
* @return {Promise<boolean>}
*/
function myPromise () {
return new Promise((res) => {
res(true)
})
}
或者
/**
* @return {Promise<number>}
*/
function myPromise () {
return new Promise((res) => {
res(1)
})
}
1.4 @example 示例注释
用于表示示例代码,通常示例的代码会另起一行编写
/**
* @author 什么当当当啊?
* @description list 数据结构 转换成 树结构
* @param {Array} data 需要转换的数据
* @param {String} id 节点 id
* @param {String} pid 父级节点 id
* @param {String} child 子树为节点对象的某个属性值
* @param {Object} labels 需要新增的字段名集合 { label: 'category_name' }
* @return {Array}
*
* @example
* formatListToTree({data: [{id:1}, {id: 2}, {id: 3, pid: 1}]})
* =>
* [ { id: 1, children: [ {id: 3, pid: 1} ] }, { id: 2 } ]
*/
function formatListToTree({
data = [],
id = "id",
pid = "pid",
child = "children",
labels = null
}) {
...
}
- @author 该类/方法的作者。
- @description 该类/方法的描述。
- @param 该类/方法的参数,可重复定义。
- @return该类/方法的返回类型。
- @example 创建例子。
1.5文件注释
/**
* @file jsdoc测试文件
* @author 什么当当当啊?
* @copyright no
* @createDate 2024-04-24 17:55
*/
1.6方法注释
/**
* @methor
* @param {Type} data={} 目标对象
* @example
* {
* target: 手机号
* }
* @return {Type} 运营商名称
* @desc 根据目标对象获取运营商
*
*/
function matchNumber(data){
return '返回数据'
}
结言
合理、规范的使用jsDoc可以让我们的代码变得通俗易懂、更加易于维护。本文中只是大致的说明了一些常见标签的使用方法以及使用规范。具体的还需要移步至官网查阅学习!jsDoc中文网 jsDoc官网