如何在使用 Typescript 编译器 api 的 printNode 函数生成代码时忽略 jsDoc?
How to ignore jsDoc while generating code using printNode function from Typescript compiler api?
Typescript 编译器API 允许我们处理抽象语法树 (AST) 并生成源代码。我们可以通过创建一个 printer
对象并使用 printNode
函数
来实现
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
printer.printNode(ts.EmitHint.Unspecified, node, sourceFile))
我面临的问题是我的 AST 在不同的地方包含很多 jsDoc,我想忽略它们并打印不带注释的代码。有什么办法可以不用手动遍历 AST 并删除 jsDoc 对象吗?
根据对 printer code 的观察(请参阅 shouldWriteComment
并按照其中的代码进行操作)它似乎不可能开箱即用。
一种破解方法是将所有包含 jsdoc 的声明的位置设置为 -1
或 node.pos = node.getStart(sourceFile)
:
> ts.createPrinter({}).printNode(node, sourceFile)
'/** Test */\r\nfunction test() {\r\n test;\r\n}\r\n'
> node.pos = -1
> ts.createPrinter({}).printNode(node, sourceFile)
'function test() {\r\n test;\r\n}\r\n'
Typescript 编译器API 允许我们处理抽象语法树 (AST) 并生成源代码。我们可以通过创建一个 printer
对象并使用 printNode
函数
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
printer.printNode(ts.EmitHint.Unspecified, node, sourceFile))
我面临的问题是我的 AST 在不同的地方包含很多 jsDoc,我想忽略它们并打印不带注释的代码。有什么办法可以不用手动遍历 AST 并删除 jsDoc 对象吗?
根据对 printer code 的观察(请参阅 shouldWriteComment
并按照其中的代码进行操作)它似乎不可能开箱即用。
一种破解方法是将所有包含 jsdoc 的声明的位置设置为 -1
或 node.pos = node.getStart(sourceFile)
:
> ts.createPrinter({}).printNode(node, sourceFile)
'/** Test */\r\nfunction test() {\r\n test;\r\n}\r\n'
> node.pos = -1
> ts.createPrinter({}).printNode(node, sourceFile)
'function test() {\r\n test;\r\n}\r\n'