Loading the TypeScript compiler into ClearScript, “WScript is undefined”, impossible task?

前端 未结 3 1710
故里飘歌
故里飘歌 2021-02-09 12:46

I tried using ClearScript to load the TypeScript compiler in order to compile some basic TypeScript code.

Unfortunately, when executing the TypeScript compiler source I

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-09 13:45

    Here's a skeletal sample using the current version of typescript.js. Note that the TypeScript API is reverse-engineered; as far as I can tell the only official interface is at the tsc command line. Also keep in mind that this is a minimal sample that does no error handling or reporting:

    using System;
    using System.IO;
    using Microsoft.ClearScript;
    using Microsoft.ClearScript.V8;
    
    namespace Test
    {
        public class TypeScriptCompiler
        {
            private readonly dynamic _compiler;
            private readonly dynamic _snapshot;
            private readonly dynamic _ioHost;
    
            public TypeScriptCompiler(ScriptEngine engine)
            {
                engine.Evaluate(File.ReadAllText("typescript.js"));
                _compiler = engine.Evaluate("new TypeScript.TypeScriptCompiler");
                _snapshot = engine.Script.TypeScript.ScriptSnapshot;
                _ioHost = engine.Evaluate(@"({
                    writeFile: function (path, contents) { this.output = contents; }
                })");
            }
    
            public string Compile(string code)
            {
                _compiler.addSourceUnit("foo.ts", _snapshot.fromString(code));
                _compiler.pullTypeCheck();
                _compiler.emitUnit("foo.ts", _ioHost);
                return _ioHost.output;
            }
        }
    
        public static class TestApplication
        {
            public static void Main()
            {
                using (var engine = new V8ScriptEngine())
                {
                    var compiler = new TypeScriptCompiler(engine);
                    Console.WriteLine(compiler.Compile("class Foo {}"));
                }
            }
        }
    }
    

提交回复
热议问题