2012-12-26 7 views
14

私はtypescriptコードを含む文字列を受け取り、JavaScriptコードを含む文字列を返すC#で関数を記述しようとしています。このためのライブラリ関数はありますか?Cでプログラムでtypescriptをコンパイルしますか?

+0

あなたはコマンドlを自動化できますineコンパイラ... – SWeko

+0

見ることができます:[この回答](http://stackoverflow.com/a/3182411/1344760) – RichardTowers

+0

@SWeko:私は 'tscを見ていますが、私は何も見ませんTSを取り込んでJSを出力します。私が見る限り、ファイルでのみ動作します。 – mpen

答えて

5

おそらくJavaScriptDotNetのようなJavaScriptインタープリターを使用して、C#のtypescriptコンパイラtsc.jsを実行することができます。

ような何か:

string tscJs = File.ReadAllText("tsc.js"); 

using (var context = new JavascriptContext()) 
{ 
    // Some trivial typescript: 
    var typescriptSource = "window.alert('hello world!');"; 
    context.SetParameter("typescriptSource", typescriptSource); 
    context.SetParameter("result", ""); 

    // Build some js to execute: 
    string script = tscJs + @" 
result = TypeScript.compile(""typescriptSource"")"; 

    // Execute the js 
    context.Run(script); 

    // Retrieve the result (which should be the compiled JS) 
    var js = context.GetParameter("result"); 
    Assert.AreEqual(typescriptSource, js); 
} 

明らかにそのコードはいくつかの深刻な作業が必要になります。このとなった場合は、その結果に確かに興味があります。

さらに、ファイルIOを必要とせずにメモリ内の文字列で操作できるように、tscを変更することもできます。

+0

ああ..出力ではなく、JavaScriptDotNetを介して 'tsc'コンパイラを実行することを意味していました。理論的には、それがうまくいくはずだと思いますが... – mpen

+2

申し訳ありませんが、より明確になっていません。一度に3つの言語について話すことは難しいです! – RichardTowers

2

TypeScriptコンパイラファイルは、正式にnode.jsまたはWindows Script Hostで実行されます。TypeScriptコンパイラファイルは、TypeScript自体で記述されています(JavaScriptに変換されます)。これには、ファイルシステムにアクセスできるスクリプトホストが必要です。

基本的に、必要なファイルシステム操作をサポートするスクリプトエンジンでタイプスクリプトをラップできるのであれば、どの言語からでも使用できます。

純粋にC#でTypeScriptをJavaScriptにコンパイルする場合は、コンパイラのC#クローンを作成することになります。

11

Processを使用してコンパイラを起動し、を一時フォルダに指定し、コンパイル済みファイルの内容を読み取ることができます。

私はそれを行うにはほとんどのアプリ作っ:例やコメントをJS string

string javascriptSource = File.ReadAllText(@"C:\tmp\test.js"); 

完全なソースを取得するには

使用

TypeScriptCompiler.Compile(@"C:\tmp\test.ts"); 

を:

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.IO; 
using System.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      try 
      { 
       // compiles a TS file 
       TypeScriptCompiler.Compile(@"C:\tmp\test.ts"); 

       // if no errors were found, read the contents of the compile file 
       string javascriptSource = File.ReadAllText(@"C:\tmp\test.js"); 
      } 
      catch (InvalidTypeScriptFileException ex) 
      { 
       // there was a compiler error, show the compiler output 
       Console.WriteLine(ex.Message); 
      } 

      Console.ReadKey(); 
     } 
    } 

    public static class TypeScriptCompiler 
    { 
     // helper class to add parameters to the compiler 
     public class Options 
     { 
      private static Options @default; 
      public static Options Default 
      { 
       get 
       { 
        if (@default == null) 
         @default = new Options(); 

        return @default; 
       } 
      } 

      public enum Version 
      { 
       ES5, 
       ES3, 
      } 

      public bool EmitComments { get; set; } 
      public bool GenerateDeclaration { get; set; } 
      public bool GenerateSourceMaps { get; set; } 
      public string OutPath { get; set; } 
      public Version TargetVersion { get; set; } 

      public Options() { } 

      public Options(bool emitComments = false 
       , bool generateDeclaration = false 
       , bool generateSourceMaps = false 
       , string outPath = null 
       , Version targetVersion = Version.ES5) 
      { 
       EmitComments = emitComments; 
       GenerateDeclaration = generateDeclaration; 
       GenerateSourceMaps = generateSourceMaps; 
       OutPath = outPath; 
       TargetVersion = targetVersion; 
      } 
     } 

     public static void Compile(string tsPath, Options options = null) 
     { 
      if (options == null) 
       options = Options.Default; 

      var d = new Dictionary<string,string>(); 

      if (options.EmitComments) 
       d.Add("-c", null); 

      if (options.GenerateDeclaration) 
       d.Add("-d", null); 

      if (options.GenerateSourceMaps) 
       d.Add("--sourcemap", null); 

      if (!String.IsNullOrEmpty(options.OutPath)) 
       d.Add("--out", options.OutPath); 

      d.Add("--target", options.TargetVersion.ToString()); 

      // this will invoke `tsc` passing the TS path and other 
      // parameters defined in Options parameter 
      Process p = new Process(); 

      ProcessStartInfo psi = new ProcessStartInfo("tsc", tsPath + " " + String.Join(" ", d.Select(o => o.Key + " " + o.Value))); 

      // run without showing console windows 
      psi.CreateNoWindow = true; 
      psi.UseShellExecute = false; 

      // redirects the compiler error output, so we can read 
      // and display errors if any 
      psi.RedirectStandardError = true; 

      p.StartInfo = psi; 

      p.Start(); 

      // reads the error output 
      var msg = p.StandardError.ReadToEnd(); 

      // make sure it finished executing before proceeding 
      p.WaitForExit(); 

      // if there were errors, throw an exception 
      if (!String.IsNullOrEmpty(msg)) 
       throw new InvalidTypeScriptFileException(msg); 
     } 
    } 

    public class InvalidTypeScriptFileException : Exception 
    { 
     public InvalidTypeScriptFileException() : base() 
     { 

     } 
     public InvalidTypeScriptFileException(string message) : base(message) 
     { 

     } 
    } 
} 
+0

これはおそらく最良の解決策ですが、私はそれをすべてメモリ(入力と出力)に保存しておきたいと思っています。 – mpen

+0

偉大な答え私は倍増することを望む! – Glenn

+0

私は、Win32Exceptionで 'ファイルが見つかりません'がありますが、私のTSファイルのパスは正しいです。私はそれが正しくないTSCコンパイラへの道だと思う。あなたはこの問題に一度直面しましたか? EDIT:TSCコンパイラのパスを直接指定しました。「このオペレーティングシステムプラットフォームでは、指定された実行可能ファイルは有効なアプリケーションではありません」というメッセージが表示されます。 –

関連する問題