Skip to content

Instantly share code, notes, and snippets.

@teppeis
Last active June 26, 2019 13:41
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teppeis/6e0f2d823a94de4ae442 to your computer and use it in GitHub Desktop.
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)
/// <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