Below is my approach in executing a TypeScript file:
npx ts-node ./tinker.ts
In the file, I am reading and analyzing the Abstract Syntax Tree (AST) of another file named sample.ts
, which contains the following line:
console.log(123)
The goal is to modify this code before executing it. For instance, I intend to replace 123 with 1337.
Consequently, when running npx ts-node ./tinker.ts
, the output displayed on the terminal should show 1337 instead.
Kindly refer to the draft provided below where I have added comments explaining the part that requires further clarification.
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 modified code!
// anticipate seeing 1337 logged!
To summarize, upon running npx ts-node ./tinker.ts
, the expected output is 1337 being displayed. What steps should I take to achieve this outcome?