有没有办法编译一个String在其 JavaScript 中包含 TypeScriptString相等的 ?
例如,在 Coffeescript(以及 LiveScript、coco 等)中,它是一个(简化的)单行代码:
jsCompiledCode = require('coffee-script').compile('do -> console.log "Hello world"', {bare:true});
TypeScript 是否可以实现类似的功能,最好不涉及文件系统?引用必须在编译时解决的其他模块是否有任何影响?
您可以使用transpileModule()
TypeScript 自带的方法。
$ 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';
编译时,您将需要 tsconfigmoduleResolution
set to "Node"
.
这将编译/执行上面的示例文件。
$ tsc compile.ts --moduleResolution Node && node compile.js
还有一些文档.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)