ts.setSyntheticLeadingComments不会删除现有评论

时间:2019-03-14 22:15:53

标签: 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]));

尝试以下变压器,看看如何完全删除注释

使用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;
}

1 个答案:

答案 0 :(得分:0)

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

实际注释不保留为AST中的节点。您可以使用getLeadingCommentRangesgetTrailingCommentRanges获取实际的源注释。

节点的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]));