我有我想transpiled到JavaScript中的打字稿文件。由于这种转换的一部分,我希望每一个功能之前,添加评论,我希望能做到这一点使用打字稿编译器API。
我尝试了两种不同的方法。其中之一是抢SourceFile
并改变其statements
,就像这样:
const program = ts.createProgram([args.input], {});
const srcFile = find(program.getSourceFiles(), (sourceFile) => !sourceFile.isDeclarationFile);
srcFile.statements = ts.createNodeArray(srcFile.statements.map((statement) => {
if (!ts.isFunctionDeclaration(statement)) {
return statement;
}
return ts.addSyntheticLeadingComment(
statement,
ts.SyntaxKind.MultiLineCommentTrivia,
"My long desired comment",
true,
);
}));
这给了我下面的错误:
TypeError: Cannot read property 'emitNode' of undefined
at getOrCreateEmitNode (/Users/.../node_modules/typescript/lib/typescript.js:52792:19)
at getOrCreateEmitNode (/Users/.../node_modules/typescript/lib/typescript.js:52801:17)
at setSyntheticLeadingComments (/Users/.../node_modules/typescript/lib/typescript.js:52918:9)
at Object.addSyntheticLeadingComment (/Users/.../node_modules/typescript/lib/typescript.js:52923:16)
at /Users/.../dist/index.js:26:15
at Array.map (<anonymous>)
at Object.<anonymous> (/Users/.../dist/index.js:21:60)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
我试着打印statement
前ts.addSyntheticLeadingComment
权利和statement
是FunctionDeclaration
,符合市场预期,尽管缺少emitNode
领域,我希望由getOrCreateEmitNode
函数创建。
我尝试第二种方法是类似的,但它运行到同一问题;而不是覆盖原来的srcFile.statement
,我有一台打印机的工作,具体如下:
const printer = ts.createPrinter(undefined, {
substituteNode: (hint, node) => {
if (ts.isFunctionDeclaration(node)) {
return ts.addSyntheticLeadingComment(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
"My long desired comment",
true,
);
}
},
});
console.log(printer.printFile(srcFile));
这给了同样的错误前面的代码。
我试图改变将输出文件非常简单:
function myFunc(a: number, b: number): number {
return a + b;
}
我真的很感激一些帮助与此有关。
最好的问候,拉杜
代节点是没有必要的。请记住,评论是不是AST的一部分,所以不要将它们添加到现有函数声明的地方陈述的阵列。取而代之的是,只需调用addSyntheticLeadingComment
的节点上,而无需使用返回值。
例如,下面的代码工作正常:
import * as ts from "typescript";
const file = ts.createSourceFile("test.ts", `function myFunc(a: number, b: number): number {
return a + b;
}`, ts.ScriptTarget.Latest, true);
const functionDec = file.statements.find(ts.isFunctionDeclaration)!;
ts.addSyntheticLeadingComment(functionDec, ts.SyntaxKind.MultiLineCommentTrivia,
"My long desired comment", true);
const printer = ts.createPrinter({ removeComments: false });
console.log(printer.printFile(file));
输出:
/*My long desired comment*/
function myFunc(a: number, b: number): number {
return a + b;
}