Node.JS 提取 class 评论
Node.JS extracting class comments
我有一个正在处理的 Node.JS 项目,它的一个非常具体的功能需要读取目录中的所有 JS 文件,提取它们的 class 注释(可能class name too), 然后将此信息存储在对象数组中,以便稍后转换为 markdown。
我的问题是 提取这些组件(例如 class 名称和 class 评论)的最佳方法是什么?
想过读文件解析语法,为什么要另起炉灶呢?如果有提取特定评论的好工具,或者解析 JS 文件的巧妙算法,我很想听听。谢谢!
您可以尝试以下库之一:
https://www.npmjs.com/package/parse-comments
查看解析器,将您的代码转换为 abstract syntax tree。
例如Esprima可以帮你解析ES6JavaScript并提取标识符和注释。
看看this live demo。对于下面的class,会生成下面的AST:
/**
*
* This is a test class
*
*/
class Foo {
bar() {
console.log('foobar');
}
}
{
"type": "Program",
"body": [
{
"type": "ClassDeclaration",
"id": {
"type": "Identifier",
"name": "Foo"
},
"superClass": null,
"body": {
...
}
]
},
"leadingComments": [
{
"type": "Block",
"value": "*\n *\n * This is a test class\n *\n ",
"range": [
0,
37
]
}
]
}
],
"sourceType": "script"
}
有一个工具可以做到这一点!查看 jsDoc。
https://github.com/jsdoc3/jsdoc
根据评论构建 HTML 网页非常简单:
npm i -g jsdoc
jsdoc yourFile.js
当然这可以与 grunt/gulp...
结合使用
我有一个正在处理的 Node.JS 项目,它的一个非常具体的功能需要读取目录中的所有 JS 文件,提取它们的 class 注释(可能class name too), 然后将此信息存储在对象数组中,以便稍后转换为 markdown。
我的问题是 提取这些组件(例如 class 名称和 class 评论)的最佳方法是什么?
想过读文件解析语法,为什么要另起炉灶呢?如果有提取特定评论的好工具,或者解析 JS 文件的巧妙算法,我很想听听。谢谢!
您可以尝试以下库之一:
https://www.npmjs.com/package/parse-comments
查看解析器,将您的代码转换为 abstract syntax tree。
例如Esprima可以帮你解析ES6JavaScript并提取标识符和注释。
看看this live demo。对于下面的class,会生成下面的AST:
/**
*
* This is a test class
*
*/
class Foo {
bar() {
console.log('foobar');
}
}
{
"type": "Program",
"body": [
{
"type": "ClassDeclaration",
"id": {
"type": "Identifier",
"name": "Foo"
},
"superClass": null,
"body": {
...
}
]
},
"leadingComments": [
{
"type": "Block",
"value": "*\n *\n * This is a test class\n *\n ",
"range": [
0,
37
]
}
]
}
],
"sourceType": "script"
}
有一个工具可以做到这一点!查看 jsDoc。 https://github.com/jsdoc3/jsdoc
根据评论构建 HTML 网页非常简单:
npm i -g jsdoc
jsdoc yourFile.js
当然这可以与 grunt/gulp...
结合使用