Created
March 13, 2025 07:33
-
-
Save azu/b2942e1a7a4a3eba04af1656be008de7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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