以编程方式将 TypeScript 字符串编译为 Javascript 字符串

Ang*_*las 5 javascript compilation typescript

有没有办法将包含 TypeScript的字符串编译为其等效的JavaScript字符串

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

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

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

D. *_*ell 16

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

$ npm install typescript
Run Code Online (Sandbox Code Playgroud)
// 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';
Run Code Online (Sandbox Code Playgroud)

编译时,您需要将 tsconfigmoduleResolution设置为"Node".

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

$ tsc compile.ts --moduleResolution Node && node compile.js
Run Code Online (Sandbox Code Playgroud)

还有一些文档


bas*_*rat 5

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

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