如何从JavaScript代码中获取函数的JSDoc文本(文档字符串)?

huangapple go评论66阅读模式
英文:

How do I get the JSDoc text (docstring) from a function inside the code in JavaScript?

问题

<span>
代表一本书。
@constructor
</span>
英文:

Considering I have a simple function, I want to extract the JSDoc string inside the code and display it in the page, like so:

/**
 * Represents a book.
 * @constructor
 */
function Book(title, author) {
  // contents
}
<span>
Represents a book.
@constructor
</span>

Can this be done?

答案1

得分: 1

In JavaScript, comments are not a part of the function's AST (Abstract Syntax Tree), they're purely metadata and most JavaScript engines don't preserve them when the function is converted to a string.

如果不是这样的话,以下代码将会生效:

function extractJSDoc(func) {
    var match = func.toString().match(/\/\*\*([\s\S]*?)\*\//);
    return (match && match.length > 1) ? match[1].trim() : '';
}

/**
 * Represents a book.
 * @constructor
 */
function Book(title, author) {
  // contents
}

document.getElementById("displayJSDoc").innerText = extractJSDoc(Book);

作为替代方案,您可以考虑将您的JSDoc注释存储在一个单独的数据结构或文件中,以便在需要时访问。另一种可能的方法是利用构建工具或转译器(如Babel)在构建步骤中提取注释并生成单独的文档文件,或者将它们注入到您需要的代码中。

英文:

In JavaScript, comments are not a part of the function's AST (Abstract Syntax Tree), they're purely metadata and most JavaScript engines don't preserve them when the function is converted to a string.

If that was not the case, the following could would work:

function extractJSDoc(func) {
    var match = func.toString().match(/\/\*\*([\s\S]*?)\*\//);
    return (match && match.length > 1) ? match[1].trim() : '';
}

/**
 * Represents a book.
 * @constructor
 */
function Book(title, author) {
  // contents
}

document.getElementById("displayJSDoc").innerText = extractJSDoc(Book);

<span id="displayJSDoc"></span>

As an alternative, you could consider storing your JSDoc comments in a separate data structure or file which you can access when needed. Another possible approach is to make use of a build tool or transpiler (like Babel) to extract the comments during a build step and generate a separate documentation file or inject them into your code where needed.

huangapple
  • 本文由 发表于 2023年5月25日 20:55:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定