在 C# 中以编程方式编译打字稿?

2024-02-15

我正在尝试用 C# 编写一个函数,该函数接受包含打字稿代码的字符串并返回包含 JavaScript 代码的字符串。有这方面的库函数吗?


您可以使用Process要调用编译器,请指定--out file.js到临时文件夹并读取编译文件的内容。

我做了一个小应用程序来做到这一点:

Usage

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

        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# 中以编程方式编译打字稿? 的相关文章

随机推荐

  • 检测用户何时截屏

    我正在寻找一种方法 让我的应用程序在用户截取屏幕截图时收到通知Command Shift 3 or Command Shift 4 一个例子是 Droplr 和 Cloud App 等应用程序 它们会自动上传截取的屏幕截图 我一直在四处寻找
  • 以编程方式设置自定义 UITabBarItem?

    在 iOS 中 TabBarController 中的 TabBar 属性是只读的 如何将自定义项目与特定视图控制器关联 如何访问 tabBar 内的 UITabBarItems 像这样 CustomView custom CustomVi
  • 如何在 R 中将因子格式转换为数字格式而不更改值? [复制]

    这个问题在这里已经有答案了 下面是数据帧 df1 我想将其中的 V2 列从因子格式转换为数字 而不更改当前值 0 0 8 5 3 df1 V1 V2 V3 X2 X3 4470 2010 03 28 0 A 21 53675 0 4471
  • 用于逐步删除随机项的首选 Scala 集合?

    我有一个需要多次迭代的算法 每次迭代都会对集合中的项目进行评分并删除得分最高的项目 我可以填充一个Vector与初始种群一起 不断将其替换为var 或者选择一个可变集合作为val 哪个可变集合最符合要求 你可以考虑一个DoubleLinke
  • 获取控制器内的环境

    我的一个控制器中有一种情况 只能通过 AJAX 访问 我有以下代码 if request gt isXmlHttpRequest response new Response response gt setContent AJAX reque
  • 如何隐藏UINavigationBar 1px底线

    我有一个应用程序 有时需要其导航栏才能与内容融为一体 有谁知道如何摆脱或改变这个烦人的小条的颜色 在下图中我遇到的情况 我正在谈论 根视图控制器 下方的这条 1px 高度线 对于 iOS 13 Use the shadowColor htt
  • 一次查找多个地方的纬度和经度

    我有一长串城镇和城市列表 我想为每个城镇添加纬度和经度信息 有谁知道一次生成此信息的最简单方法 也可以看看对多个地址进行地理编码 https stackoverflow com questions 396819 geocode multip
  • 使用scale_fill_binned()时如何使用特定的填充颜色?

    我想使用我自己的填充颜色 例如 c red blue grey50 black 使用函数时scale fill binned 在 ggplot 代码中 我怎样才能做到这一点 这是一个最小的可重现示例 library tidyverse da
  • 接受可变数量参数的函数

    在本文档中 https developer apple com library prerelease ios documentation Swift Conceptual Swift Programming Language GuidedT
  • 我可以用 AngularJS 更改 Accept-Language 请求标头吗

    有没有办法更改或编辑我发送到 API 的接受语言标头 javascript Jquery 或 Angular 有没有办法 我不想发送默认的 而是发送我的 Cookie 的 在 AngularJS 中 您可以使用以下方法设置通用标头 http
  • 如何访问 Gradle 使用的“java.home”?

    gradlew properties显示没有具有以下值的属性 JAVA HOME 并且以下发出错误 指示不存在此类属性 println org gradle java home println gradle java home printl
  • 在 Google Chrome 扩展中使用 jQuery.ajax

    我使用 jquery ajax 函数将数据从 google chrome 扩展发布到我的网络服务 代码如下 ajax type POST url serviceUrl data data success function msg if ty
  • 将季度/年份格式转换为日期

    我创建了一个函数 将季度年格式的向量强制转换为日期向量 quarter to date c Q1 13 Q2 14 1 2013 03 01 2014 06 01 这是我的函数的代码 quarter to date lt function
  • 用鼠标拖动滚动

    我正在尝试制作一个可滚动面板 但没有滚动条 并通过用鼠标垂直拖动来滚动 这是到目前为止有人帮助我做的 private void panel1 MouseEnter object sender EventArgs e panel1 AutoS
  • 哪个更快? ByVal 还是 ByRef?

    在 VB NET 中 使用方法参数速度更快 ByVal or ByRef 另外 哪个在运行时消耗更多资源 RAM 我通读了这个问题 https stackoverflow com questions 290189 best practice
  • 多对多 EF7

    Models public partial class Film public int FilmID get set public virtual ICollection
  • 单例模板作为 C++ 中的基类[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 根据C 单例设计模式 https stackoverflow com questions 1008019 c singleton design
  • 通过 Socket.io 更新 React 状态

    我的 React 组件使用来自 socket io 的数据作为状态 我不确定如何在更新数据时更新状态而不重新渲染整个组件 示例代码 var socket io var data components key name markup sock
  • nginx 将 POST 请求重定向到 GET 请求

    我有 Rails 4 1 应用程序运行puma网络服务器 我使用 nginx 作为代理服务器 几天前 一切都进展顺利 我更新了我的应用程序 突然有些POST请求开始重定向到相同的网址 但作为GET要求 我尝试回滚到以前的工作版本 但没有成功
  • 在 C# 中以编程方式编译打字稿?

    我正在尝试用 C 编写一个函数 该函数接受包含打字稿代码的字符串并返回包含 JavaScript 代码的字符串 有这方面的库函数吗 您可以使用Process要调用编译器 请指定 out file js到临时文件夹并读取编译文件的内容 我做了