以编程方式将TypeScript字符串编译为Javascript字符串
Compile a TypeScript String to a Javascript String programmatically
是否有方法将包含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
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- jQuery中是否内置了任何字符串格式化函数
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- ng打开空字符串
- 正则表达式在字符串中找到base64
- 如何将字符串值从php页面发送到java脚本页面
- 检测在angular中传递给$compile的字符串的最佳方法是可编译的
- 是否可以将角度模板编译为最终的 html 字符串
- AngularJs - 从编译的 HTML/变量中获取一个字符串
- 在CoffeeScript中,是否存在一个'官方'在运行时而不是编译时插入字符串的方法
- 在没有指令的情况下将模板编译成angular字符串
- 以编程方式将TypeScript字符串编译为Javascript字符串
- jquery/javascript文件验证2字符串编译(文件扩展)失败
- 在Angular中编译HTML字符串模板
- Es6模板字符串+短对象文字编译失败[gulp, babel]
- 如何将html表单模板编译成html字符串
- Javascript验证,其中字符串仅由任意数量的空格编译
- 将角度模板编译为html的正确方法,将结果转换为字符串
- Angular:从一个字符串编译到另一个字符串
- 如何在Angular中编译包含指令的字符串;$compile和$interpolate似乎不起作用