javascript JSDoc在文档中添加真实的代码

vhmi4jdf  于 12个月前  发布在  Java
关注(0)|答案(6)|浏览(80)

你知道JSDoc中是否有某种<code />标记吗?我需要在我的文档中添加一些代码,如下所示:

/**
 * This function does something see example below:
 *
 * var x = foo("test"); //it will show "test" message
 *
 * @param {string} str: string argument that will be shown in message
 */
function foo(str)
{
   alert(str);
}

我需要在注解中的代码被JSDoc显示为代码(如果不是语法突出显示,至少像预先格式化或灰色背景的东西)。

zvokhttg

zvokhttg1#

@examplehttp://code.google.com/p/jsdoc-toolkit/wiki/TagExample

/**
 * This function does something see example below:
 * @example
 * var x = foo("test"); //it will show "test" message
 *
 * @param {string} str: string argument that will be shown in message
 */
function foo(str)
{
   alert(str);
}
7y4bm7vi

7y4bm7vi2#

使用

<pre><code>

....

</code></pre>

这是在许多官方文档中使用的,并且将例如通过一些工具接收语法高亮显示

y4ekin9u

y4ekin9u3#

Jsdoc3有一个markdown插件,但默认情况下它是关闭的。启用它的默认配置文件./node_modules/jsdoc/conf.json.EXAMPLE通过.

"plugins": [
    "plugins/markdown"
],

...而且你有很好的文档语法支持,包括代码。Markdown使用三个反引号(`````)来划分代码块。对于使用原始示例:

/**
* This function does something see example below:
* ```
* var x = foo("test"); //it will show "test" message
* ```
* @param {string} str: string argument that will be shown in message
*/
50pmv0ei

50pmv0ei4#

您可以将任何HTML放入JSDoc,它将被复制出来。以下是我使用的示例:

/** 
 * The ReplaceSlang method replaces the string &quot;hi&quot; with &quot;hello&quot;.
 *   <script language="javascript">
 *     function testFunc() {
 *       alert(ReplaceSlang(prompt("Enter sample argument")));
 *     }
 *   </script>
 *   <input type="button" value="Test" onclick="testFunc()" />
 * @param {String} str The text to transform
 * @return {String}
 */
exports.ReplaceSlang = function(str) {
  return str.replace("hi", "hello");
};

要确保按钮不在摘要中,请在其前面添加一个句子和一个点(.)。
您需要找到某种方法将JavaScript文件包含在JSDoc的输出中,以便加载它们。(您的代码在JSDoc的输出中不作为JavaScript存在-您可以为此修改模板:见JsPlate documentation

suzh9iv8

suzh9iv85#

对于jsdoc3<code>...</code>似乎工作得很好。它还保持代码内联,同时添加<pre>创建一个段落(这是它应该做的)。Browser support似乎是好的,所以我没有看到任何理由不使用它。

zphenhs4

zphenhs46#

使用@example适用于大多数情况,但HTML保留字符需要转换为HTML实体:&lt;&gt;等等,否则HTML将被呈现而不显示为代码。
从链接的文档中:

/**
 * Solves equations of the form a * x = b
 * @example
 * // returns 2
 * globalNS.method1(5, 10);
 * @example
 * // returns 3
 * globalNS.method(5, 15);
 * @returns {Number} Returns the value of x for the equation.
 */
globalNS.method1 = function (a, b) {
    return b / a;
};

带标题的示例:

/**
 * Solves equations of the form a * x = b
 * @example <caption>Example usage of method1.</caption>
 * // returns 2
 * globalNS.method1(5, 10);
 * @returns {Number} Returns the value of x for the equation.
 */
globalNS.method1 = function (a, b) {
    return b / a;
};

相关问题