TypeScript compiler api: get position in generated code of a specific AST node

Viewed 492

My goal is to get the location (start and end) of a specific TypeScript AST node in the emitted (JavaScript) file.

Take this code for example:

const program = ts.createProgram(tsconfig.fileNames, tsconfig.options);
const aNode = program.getSourceFiles()[0].getChildAt(1);
const emittedFiles = [];
program.emit(/*targetSourceFile */undefined, /*writeFile*/ (fileName, content) => emittedFiles.push({ fileName, content }));

How can i get the location of the emitted code represented by aNode?

The way i'm trying this now is by capturing the source map file and reverse engineer the location using https://npmjs.org/package/source-map. However the source map file only gives me an estimation of the location.

Is there any way to reverse engineer the exact location using the source map file, or intercepting the exact location as the node is written to the JavaScript output during emit phase?

1 Answers
Related