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

Compile a TypeScript String to a Javascript String programmatically

本文关键字:字符串 编译 Javascript TypeScript 编程 方式      更新时间:2023-09-26

是否有方法将包含TypeScript的String编译为等效的JavaScriptString

例如,在Coffeescapet(以及LiveScript、coco等)中,它有一个(简化的)单行:

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

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

您可以使用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

还有一些文档。

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

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