It\'s pretty easy to do this with coffee-script.
var coffee = require(\'coffee-script\');
coffee.compile(\"a = 1\");
//=> \'(function() {\\n var a;\\n\\n a
Official documentation about how to use TypeScript transpiler API to generate JavaScript source from a .ts file:
https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-transpiling-a-single-file
Official documentation about how to use TypeScript compiler API to compile a .ts file or a TS project to
https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-a-minimal-compiler
(the later doesn't answer the original question but is very common to access /modify the AST and then transpile to object language so it could be usefull)
better-require could help you achieve this.
It lets you require() typescript files - no pre-compilation needed - and a bunch of other file formats (coffeescript, clojurescript, yaml, xml, etc.)
require('better-require')();
var myModule = require('./mymodule.ts');
Disclosure: I wrote better-require.
It seems that nowadays there is a simpler solution, you can do:
let ts = require('typescript');
let source = ts.transpileModule('class Test {}', {}).outputText;
This results in:
"use strict";
var Test = (function () {
function Test() {
}
return Test;
}());
Since TypeScript's NPM module doesn't export any public interface, the only way to do this currently is to execute the tsc
process.
var exec = require('child_process').exec;
var child = exec('tsc main.ts',
function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
An issue has been opened to request a public interface for the TypeScript module.
Not answering the question directly, but since Googling for "run TypeScript from node directly" brings up this StackOverflow page, I figure I should add that you're able to do this with ts-node: https://github.com/TypeStrong/ts-node
Check this github project by niutech, it can convert TypeScript code to JS code on the fly in browser, but I guess it can be easily be modified to work in node.js.
I found it while I'm investigating the possibility of support TypeScript in my live, firebug-inspired code editor.