【问题标题】:Compile a TypeScript String to a Javascript String programmatically以编程方式将 TypeScript 字符串编译为 Javascript 字符串
【发布时间】:2013-07-31 16:40:25
【问题描述】:

有没有办法将包含 TypeScript 的 String 编译为其 JavaScript String 等效项?

例如,在 Coffeescript(和 LiveScript、coco 等)中,它是一个(简化的)单线:

jsCompiledCode = require('coffee-script').compile('do -> console.log "Hello world"', {bare:true});

可以为 TypeScript 实现类似的东西,最好不涉及文件系统吗?引用其他必须在编译时解决的模块有什么影响吗?

【问题讨论】:

    标签: javascript compilation typescript


    【解决方案1】:

    你可以使用 TypeScript.Api nodejs 包:https://npmjs.org/package/typescript.api

    特别检查这个功能:https://github.com/sinclairzx81/typescript.api#compile

    【讨论】:

    • 我希望有一个没有第三方包的解决方案,可以轻松用于 urequire 资源转换器 (urequire.org/resourceconverters.coffee)。我看到 TypeScript 对它的模块非常固执……我猜想在 uRequire 中支持跨 nodejs/AMD/typescript 需要做很多工作……
    【解决方案2】:

    你可以使用 TypeScript 自带的transpileModule() 方法。

    $ npm install typescript
    
    // compile.ts
    
    import * as ts from "typescript";
    
    function tsCompile(source: string, options: ts.TranspileOptions = null): string {
        // Default options -- you could also perform a merge, or use the project tsconfig.json
        if (null === options) {
            options = { compilerOptions: { module: ts.ModuleKind.CommonJS }};
        }
        return ts.transpileModule(source, options).outputText;
    }
    
    // Make sure it works
    const source = "let foo: string  = 'bar'";
    
    let result = tsCompile(source);
    
    console.log(result); // var foo = 'bar';
    

    编译时,您需要将 tsconfig moduleResolution 设置为 "Node"

    这将编译/执行上面的示例文件。

    $ tsc compile.ts --moduleResolution Node && node compile.js
    

    还有一些documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2020-11-27
      相关资源
      最近更新 更多