Last active
June 26, 2019 13:41
-
-
Save teppeis/6e0f2d823a94de4ae442 to your computer and use it in GitHub Desktop.
Mimimal code to compile TypeScript string (from https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API)
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
/// <reference path="typings/node/node.d.ts" /> | |
/// <reference path="typings/typescript/typescript.d.ts" /> | |
import ts = require("typescript"); | |
import fs = require("fs"); | |
import path = require("path"); | |
function transform(contents: string, libSource: string, compilerOptions: ts.CompilerOptions = {}) { | |
// Generated outputs | |
var outputs = []; | |
// Create a compilerHost object to allow the compiler to read and write files | |
var compilerHost = { | |
getSourceFile: function (filename, languageVersion) { | |
if (filename === "file.ts") | |
return ts.createSourceFile(filename, contents, compilerOptions.target, "0"); | |
if (filename === "lib.d.ts") | |
return ts.createSourceFile(filename, libSource, compilerOptions.target, "0"); | |
return undefined; | |
}, | |
writeFile: function (name, text, writeByteOrderMark) { | |
outputs.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); | |
}, | |
getDefaultLibFilename: function () { return "lib.d.ts"; }, | |
useCaseSensitiveFileNames: function () { return false; }, | |
getCanonicalFileName: function (filename) { return filename; }, | |
getCurrentDirectory: function () { return ""; }, | |
getNewLine: function () { return "\n"; } | |
}; | |
// Create a program from inputs | |
var program = ts.createProgram(["file.ts"], compilerOptions, compilerHost); | |
// Query for early errors | |
var errors = program.getDiagnostics(); | |
// Do not generate code in the presence of early errors | |
if (!errors.length) { | |
// Type check and get semantic errors | |
var checker = program.getTypeChecker(true); | |
errors = checker.getDiagnostics(); | |
// Generate output | |
checker.emitFiles(); | |
} | |
return { | |
outputs: outputs, | |
errors: errors.map(function (e) { return e.file.filename + "(" + e.file.getLineAndCharacterFromPosition(e.start).line + "): " + e.messageText; }) | |
}; | |
} | |
// Calling our transform function using a simple TypeScript variable declarations, | |
// and loading the default library like: | |
var source = "var x: number = 'string'"; | |
var libSource = fs.readFileSync(path.join(path.dirname(require.resolve('typescript')), 'lib.d.ts')).toString(); | |
var result = transform(source, libSource); | |
console.log(JSON.stringify(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment