【发布时间】:2019-03-15 21:12:07
【问题描述】:
说明
你好,
我正在尝试构建一些可以在函数之上添加 cmets 的东西。
不幸的是,ts.setSyntheticLeadingComments 似乎不允许我替换现有的 cmets。
我试过了:
ts.setSyntheticLeadingComments(node, [])ts.setSyntheticLeadingComments(node, undefined)node = ts.setSyntheticLeadingComments(node, [])
但这些都不起作用。最终,我的目标是能够用新的 cmets 替换现有的 cmets。
有什么想法吗?谢谢??????
复制
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]));
试试下面的转换器,看看如何完全没有移除 cmets
使用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;
}
【问题讨论】:
-
这里有一个 GitHub 问题:github.com/Microsoft/TypeScript/issues/30191
-
现在我看起来更好它相同的内容:D
-
您要添加 jsdocs 吗?看看这个问题:github.com/Microsoft/TypeScript/issues/17146 -- 顺便说一句,它们存储在 ast 中,但常规 cmets 不是。
标签: typescript typescript-compiler-api