20

typescript コードを含む文字列を受け取り、JavaScript コードを含む文字列を返す関数を C# で作成しようとしています。これのためのライブラリ関数はありますか?

4

3 に答える 3

13

Processコンパイラを呼び出し、--out file.js一時フォルダに指定して、コンパイルされたファイルの内容を読み取るために使用できます。

私はそれを行うための小さなアプリを作りました:

使用法

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

を取得するにはJS string

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

例とコメントを含む完全なソース:

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)
        {

        }
    }
}
于 2013-07-08T18:54:57.487 に答える
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);
}

明らかに、そのコードには深刻な作業が必要です。これ実現可能であることが判明した場合、私は確かにその結果に興味があります.

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

于 2012-12-26T21:33:33.817 に答える
2

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

基本的に、必要なファイル システム操作をサポートするスクリプト エンジンでラップできる限り、任意の言語から TypeScript を実行できます。

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

于 2012-12-26T22:52:32.793 に答える