Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use TypeScript compiler from node

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 = 1;\n\n}).call(this);\n'

Is there a way to do this with typescript?

Edit: also posted on codeplex

like image 341
Ilia Choly Avatar asked Oct 04 '12 14:10

Ilia Choly


People also ask

CAN node execute TypeScript?

Overview. ts-node is a TypeScript execution engine and REPL for Node. js. It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.

How do I get a TypeScript compiler?

TypeScript is available as a package on the npm registry available as "typescript" . You will need a copy of Node. js as an environment to run the package. Then you use a dependency manager like npm, yarn or pnpm to download TypeScript into your project.


2 Answers

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;
}());
like image 143
topek Avatar answered Sep 20 '22 09:09

topek


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.

like image 45
joshuapoehls Avatar answered Sep 20 '22 09:09

joshuapoehls