Created
June 26, 2023 07:19
-
-
Save igrek8/b76c66110fb425fd3ad8f1e16900d6ce to your computer and use it in GitHub Desktop.
TypeScript Compiler API: Check language syntax using string content
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 ts from "typescript"; | |
const code = `type A = string;`; | |
const sourceFile = ts.createSourceFile("source.ts", code, ts.ScriptTarget.Latest); | |
const host = ts.createCompilerHost({}); | |
const getSourceFile = host.getSourceFile; | |
host.getSourceFile = function (name, languageVersion) { | |
return name === sourceFile.fileName ? sourceFile : getSourceFile.call(host, name, languageVersion); | |
}; | |
const program = ts.createProgram([sourceFile.fileName], { noEmit: true }, host); | |
const diagnostics = ts.getPreEmitDiagnostics(program); | |
if (diagnostics.length > 0) { | |
console.error("Syntax errors found:"); | |
diagnostics.forEach((diagnostic) => { | |
if (!diagnostic.start) return; | |
if (!diagnostic.file) return; | |
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); | |
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); | |
console.error(` Error at ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment