0

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?

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer David. Moving code up would help with comments above declarations of types but not above properties if I understand correctly. In the meantime - by the way - I found that removing jsDoc properties from AST doesn't affect output, because it seems to be generated from text property, not from AST, surprisingly...
Yeah, the jsdocs are emitted from the source file text based on the position of the node. The ts compiler is designed for whatever works best for compiling the code so I guess they decided to do that because it left the jsdoc text the same more reliably. Also, doing -1 won't move the code up, but will just cause the printer to not emit any comments for that node. -1 is what's used by default for the pos for nodes created with factory functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.