I have a TypeScript file that needs to be transpiled into JavaScript. As part of this conversion process, I want to include a comment before every function using the TypeScript Compiler API.
I experimented with two different methods. One involved accessing the SourceFile
and modifying its statements
like so:
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 desired comment",
true,
);
}));
This approach resulted in the following error:
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)
Prior to the ts.addSyntheticLeadingComment
, when I printed the statement
, it was indeed a
FunctionDeclaration</code as expected, but lacked the <code>emitNode
field that should have been created by the getOrCreateEmitNode
.
The second method I attempted followed a similar path, encountering the same issue. Rather than replacing the original srcFile.statement
, I used a printer instead:
const printer = ts.createPrinter(undefined, {
substituteNode: (hint, node) => {
if (ts.isFunctionDeclaration(node)) {
return ts.addSyntheticLeadingComment(
node,
ts.SyntaxKind.MultiLineCommentTrivia,
"Desired comment here",
true,
);
}
},
});
console.log(printer.printFile(srcFile));
However, this also produced the same error as seen in previous code attempts.
The TypeScript file I am attempting to modify is quite simple:
function myFunc(a: number, b: number): number {
return a + b;
}