Im executing a ts file with:
npx ts-node ./tinker.ts
The file reads and parses the AST of another file sample.ts
containing a single line:
console.log(123)
Next it should execute that code, but manipulate it before doing so - for example I want to change 123 to 1337.
So, the final result of running npx ts-node ./tinker.ts
should be that 1337 is printed in my terminal. Please see my draft below. The code comments is the part that I could not understand how to do.
sample.ts
console.log(123);
tinker.ts
import * as fs from "fs";
const ts = require("typescript");
const path = "./sample.ts";
const code = fs.readFileSync(path, "utf-8"); // "console.log(123)"
const node = ts.createSourceFile("TEMP.ts", code, ts.ScriptTarget.Latest);
let logStatement = node.statements.at(0);
logStatement.expression.arguments.at(0).text = "1337";
// execute the manipulated code!
// expect to see 1337 logged!
To reiterate, running npx ts-node ./tinker.ts
should log 1337. How can I achieve this?