Skip to content

Instantly share code, notes, and snippets.

@jerrylususu
Last active March 1, 2023 15:22
Show Gist options
  • Save jerrylususu/af4ed41302123292983f9b4fd81909ef to your computer and use it in GitHub Desktop.
Save jerrylususu/af4ed41302123292983f9b4fd81909ef to your computer and use it in GitHub Desktop.
TS logging idea
const ts = require("typescript");
const {readFileSync} = require("fs");
const filename = "source.ts";
// tsconfig
const options = {"target": "ESNext",
"module": "ESNext",
"moduleResolution": "node"}
const compilerHost = {
...ts.createCompilerHost(options),
getSourceFile: (fileName, languageVersion)=>ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.Latest, true)
}
const program = ts.createProgram([filename], options, compilerHost);
const sourceFile = program.getSourceFile(filename);
const { transformed } = ts.transform(sourceFile, [
context => {
return sourceFile => {
const visitor = (node) => {
// console.log(node.kind, `\t# ts.SyntaxKind.${ts.SyntaxKind[node.kind]}`);
if (ts.isCallExpression(node)) {
if (node.getChildCount() >= 2 && ts.isPropertyAccessExpression(node.getChildAt(0))) {
const pa = node.getChildAt(0);
const [obj, dot, methodName, ...rest] = pa.getChildren();
if (obj.getText() === "console" && methodName.getText() === "log") {
// now that's it
const file = node.getSourceFile();
const filenameArr = file.fileName.split("/");
const filename = filenameArr[filenameArr.length - 1];
const position = file.getLineAndCharacterOfPosition(node.getStart());
const stringliteral = ts.createStringLiteral(`(${filename}:${position.line+1}:${position.character})`);
// console.log("type arguments", node.typeArguments); // 一直是 undefined?
const newCall = ts.createCall(node.expression, node.typeArguments, [stringliteral, ...node.arguments]);
return newCall;
}
}
}
return ts.visitEachChild(node, visitor, context);
};
return ts.visitNode(sourceFile, visitor);
};
},
]);
const printer =ts.createPrinter();
const code = printer.printNode(false, transformed[0], transformed[0]);
console.log(code);
const hello = true as boolean;
console.log("hello world!" as string, "good night");
const hi = "here" as string;
const what = {} as any;
console.log(`value: ${what.hi || 'not found'}`);
function fn() {
console.log("even works inside!");
}
const hello = true as boolean;
console.log("(source.ts:2:0)", ("hello world!" as string), "good night");
const hi = "here" as string;
const what = {} as any;
console.log("(source.ts:5:0)", `value: ${what.hi || 'not found'}`);
function fn() {
console.log("(source.ts:7:4)", "even works inside!");
}