Skip to content

Instantly share code, notes, and snippets.

@azu
Created March 13, 2025 07:33
Show Gist options
  • Save azu/b2942e1a7a4a3eba04af1656be008de7 to your computer and use it in GitHub Desktop.
Save azu/b2942e1a7a4a3eba04af1656be008de7 to your computer and use it in GitHub Desktop.
import * as ts from "typescript";
const getLineTextFromFilePosition = (
file: ts.SourceFile,
{ line, character }: ts.LineAndCharacter,
): string => {
const lines = file.getFullText().split("\n");
return lines[line]?.slice(character) ?? "";
};
function compile(fileNames: string[], options: ts.CompilerOptions): void {
let program = ts.createProgram(fileNames, options);
let emitResult = program.emit();
let allDiagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
allDiagnostics.forEach((diagnostic) => {
if (diagnostic.file) {
let { line, character } = ts.getLineAndCharacterOfPosition(
diagnostic.file,
diagnostic.start!,
);
let message = ts.flattenDiagnosticMessageText(
diagnostic.messageText,
"\n",
);
const lineText = getLineTextFromFilePosition(diagnostic.file, {
line,
character,
});
console.log(
`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}
----
${lineText}
----`,
);
} else {
console.log(
ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
);
}
});
let exitCode = emitResult.emitSkipped ? 1 : 0;
console.log(`Process exiting with code '${exitCode}'.`);
process.exit(exitCode);
}
const tsconfig = ts.readConfigFile("tsconfig.json", ts.sys.readFile);
const config = ts.parseJsonConfigFileContent(tsconfig.config, ts.sys, "./");
compile(config.fileNames, config.options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment