Typescript compiler API allows us to process abstract syntax tree (AST) and generate source code. We can do it by creating a printer
object and using printNode
function
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
printer.printNode(ts.EmitHint.Unspecified, node, sourceFile))
The problem I'm facing is that my AST contains lots of jsDoc in various places and I want to ignore them and print code without comments. Is there any way to do it without manually traversing the AST and removing jsDoc objects?
CodePudding user response:
Based on looking at the printer code (see shouldWriteComment
and follow the code out of there) it doesn't seem possible out of the box.
One way you could hack this is to set the positions of all declarations that have jsdocs to be -1
or 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'