Use TypeScript compiler from node

后端 未结 6 1683
既然无缘
既然无缘 2021-02-02 17:30

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          


        
相关标签:
6条回答
  • 2021-02-02 17:35

    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)

    0 讨论(0)
  • 2021-02-02 17:48

    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.

    0 讨论(0)
  • 2021-02-02 17:49

    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;
    }());
    
    0 讨论(0)
  • 2021-02-02 17:49

    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.

    0 讨论(0)
  • 2021-02-02 17:51

    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

    0 讨论(0)
  • 2021-02-02 17:53

    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.

    0 讨论(0)
提交回复
热议问题