根据其官网(https://jsdoc.app/index.html)的介绍,JSDoc 是一个针对 JavaScript 的 API 文档生成器,类似于 Java 中的 Javadoc 或者 PHP 中的 phpDocumentor;在源代码中添加指定格式的注释,JSDoc 工具便会自动扫描你的代码并生成一个 API 文档网站(在指定目录下生成相关的网页文件);
生成 API 文档只是一方面,其更主要的贡献在于对代码注释格式进行了规范化,你可能没用过,但多半曾经在某个地方的源码中见过类似于下面的注释格式:
1 2 3 4 5 6 7 8 9
/** * Returns the sum of a and b * @param {number} a * @param {number} b * @returns {number} */ functionsum(a, b) { return a + b; }
使用
工具的使用很简单,首先安装它:
1
npm install -g jsdoc
其次假设在一个名为 doc.js 的文件中书写以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * Returns the sum of a and b * @param {number} a * @param {number} b * @returns {number} */ functionsum(a, b) { return a + b; } /** * Return the diff fo a and b * @param {number} a * @param {number} b * @returns {number} */ functiondiff(a, b) { return a - b; }
然后就是在当前目录执行以下命令:
1
jsdoc doc.js
最后就会在当前目录下生成一个名为 out 的目录(也可以另外指定),当前目录内容就会变成像下面这样:
/** * @license * Copyright (c) 2015 Example Corporation Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * ... */
/** * 标签后跟参数类型,然后是参数名,最后是参数描述 * @param {number} a 这里写变量的描述 * @param {string} b - 或者加上连字符便于阅读 * @param {string} c - 又或者这个参数有一个很长很长很长 * 很长很长很长很长很长非常长的描述,可以这样占用多行 */ functionmyFn(a, b, c) {}
/** * 传入的参数是个对象 * @param {object} option - 传入的对象参数 * @param {string} option.name - 对象的 name 属性 * @param {number} option.age - 对象的 age 属性 */ functionmyFn(option) { var name = option.name; var age = option.age; }
/** * 传入的参数是个字符串组成的数组 * @param {string[]} arr - 传入的对象参数 */ functionmyFn(arr) { var name = option.name; var age = option.age; }
/** * 表示某个参数是可选的 * @param {number} a - 这是必填参数 * @param {number} [b] - 这是可选参数 * @param {number=} c - 可选参数的另一种表示 */ functionmyFn(a, b, c) {}
/** * 表示可选参数的默认值 * @param {number} a * @param {number} [b=3] - 默认值为 3 */ functionmyFn(a, b) {}
/** * 参数类型的各种表示 * @param {number} a - 类型为数字 * @param {number|string} b - 类型为数字或字符串 * @param {?number} c - 类型为数字或者为空(null) * @param {!number} d - 类型为数字且不为空 * @param {*} e - 类型不做限制,即可以为任意类型 */ functionmyFn(a, b, c, d, e) {}
/** * 表示具有任意多个参数的函数 * 下面的函数返回所有传入参数的和 * @param {...number} num - 参数个数任意,但是都是数字类型 */ functionsum(num) { var len = arguments.length; var result = 0; for (let i = 0; i < len; i++) { result += arguments[i]; } return result; }