ts.setSyntheticLeadingComments 不会删除现有评论

Fla*_*rne 2 typescript typescript-compiler-api

描述

嘿,

我正在尝试构建一些可以在函数之上添加注释的东西。不幸的是,似乎ts.setSyntheticLeadingComments不允许我替换现有的评论。

我努力了:

  • ts.setSyntheticLeadingComments(node, [])
  • ts.setSyntheticLeadingComments(node, undefined)
  • node = ts.setSyntheticLeadingComments(node, [])

但这些都不起作用。最终,我的目标是能够用新评论替换我本来生成的现有评论。

任何想法 ?谢谢

再生产

const transformFactory = (context: ts.TransformationContext) => (
  rootNode: ts.SourceFile
): ts.SourceFile => {
  const visit = (node: ts.Node) => {
    node = ts.visitEachChild(node, visit, context);

    ts.setSyntheticLeadingComments(node, []);

    return node;
  };

  return ts.visitNode(rootNode, visit);
};

const sourceFile = ts.createSourceFile(
  path,
  source,
  ts.ScriptTarget.ESNext,
  true,
  ts.ScriptKind.TS
);
const result = ts.transform(sourceFile, [transformFactory]);
const resultPrinter = ts.createPrinter({ removeComments: false });

console.log(resultPrinter.printFile(result.transformed[0]));
Run Code Online (Sandbox Code Playgroud)

尝试以下转换器,看看如何完全不删除任何注释

使用ts.createPrinter(..., { substituteNode(hint, node) { ... } })也没有帮助

边注

似乎也ts.getSyntheticLeadingComments()没有按照我期望的方式工作。它总是返回undefined,这导致我使用以下实用程序,尽管我不确定完全理解它的目的(借自https://github.com/angular/tsickle/blob/6f5835a644f3c628a61e3dcd558bb9c59c73dc2f/src/transformer_util.ts# L257-L266

/**
 * A replacement for ts.getLeadingCommentRanges that returns the union of synthetic and
 * non-synthetic comments on the given node, with their text included. The returned comments must
 * not be mutated, as their content might or might not be reflected back into the AST.
 */
export function getAllLeadingComments(node: ts.Node):
    ReadonlyArray<Readonly<ts.CommentRange&{text: string}>> {
  const allRanges: Array<Readonly<ts.CommentRange&{text: string}>> = [];
  const nodeText = node.getFullText();
  const cr = ts.getLeadingCommentRanges(nodeText, 0);
  if (cr) allRanges.push(...cr.map(c => ({...c, text: nodeText.substring(c.pos, c.end)})));
  const synthetic = ts.getSyntheticLeadingComments(node);
  if (synthetic) allRanges.push(...synthetic);
  return allRanges;
}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 6

问题是您期望这些*SyntheticLeadingComments函数会影响源注释。他们不会。它们只会影响之前综合的注释(即您在代码中添加的注释)。

实际评论不会作为节点保存在 AST 中。您可以使用getLeadingCommentRanges和获取实际的源注释getTrailingCommentRanges

节点有startend位置,不包含任何注释。节点还有一个 fullStart,它是包含所有前导注释的位置。当输出节点时,这就是打字稿如何将注释复制到输出的方式。

如果我们使用setTextRange设置节点的范围来排除这些现有注释,结果是我们有效地将它们从输出中删除,并且我们可以使用以下命令添加新注释setSyntheticLeadingComments

import * as ts from 'typescript'

const transformFactory = (context: ts.TransformationContext) => (
    rootNode: ts.SourceFile
): ts.SourceFile => {
    const visit = (node: ts.Node) => {
        node = ts.visitEachChild(node, visit, context);
            if(ts.isFunctionDeclaration(node)) {
            let sourceFileText = node.getSourceFile().text;
            const existingComments = ts.getLeadingCommentRanges(sourceFileText, node.pos);
            if (existingComments) {
                // Log existing comments just for fun 
                for (const comment of existingComments) {
                    console.log(sourceFileText.substring(comment.pos, comment.end))
                }
                // Comment also attaches to the first child, we must remove it recursively.
                let removeComments =  (c: ts.Node) => {
                    if (c.getFullStart() === node.getFullStart()) {
                        ts.setTextRange(c, { pos: c.getStart(), end: c.getEnd() });
                    }
                    c = ts.visitEachChild(c, removeComments, context);
                    return c;
                }
                ts.visitEachChild(node, removeComments, context);
                ts.setTextRange(node, { pos: node.getStart(), end: node.getEnd() })
                ts.setSyntheticLeadingComments(node, [{
                    pos: -1,
                    end: -1,
                    hasTrailingNewLine: false,
                    text: "Improved comment",
                    kind: ts.SyntaxKind.SingleLineCommentTrivia
                }]);

            }
        }
        return node;
    };

    return ts.visitNode(rootNode, visit);
};

const sourceFile = ts.createSourceFile(
    "path.ts",
    `
// Original comment
function test () {

}
`,
    ts.ScriptTarget.ESNext,
    true,
    ts.ScriptKind.TS
);
const result = ts.transform(sourceFile, [transformFactory]);
const resultPrinter = ts.createPrinter({ removeComments: false });

console.log("!");
console.log(resultPrinter.printFile(result.transformed[0]));
Run Code Online (Sandbox Code Playgroud)