是否可以将我的Typescript代码保存在字符串中并在运行时进行评估?举个简单的例子:
let code: string = `({
Run: (data: string): string => {
console.log(data); return Promise.resolve("SUCCESS"); }
})`;
Run Code Online (Sandbox Code Playgroud)
然后像这样运行:
let runnalbe = eval(code);
runnable.Run("RUN!").then((result:string)=>{console.log(result);});
Run Code Online (Sandbox Code Playgroud)
应打印:
RUN!SUCCESS
Run Code Online (Sandbox Code Playgroud)
Sar*_*ana 15
在正式打字编译器API提供了一种transpile源字符串:
import * as ts from "typescript";
let code: string = `({
Run: (data: string): string => {
console.log(data); return Promise.resolve("SUCCESS"); }
})`;
let result = ts.transpile(code);
let runnalbe :any = eval(result);
runnalbe.Run("RUN!").then((result:string)=>{console.log(result);});
Run Code Online (Sandbox Code Playgroud)
是否可以将我的 Typescript 代码保存在字符串中并在运行时对其进行评估
是的。通过使用 TypeScript 编译器的transpile
功能。
检查 TypeScript - 脚本:https://github.com/basarat/typescript-script其核心很简单ts.transpile
: https: //github.com/basarat/typescript-script/blob/163388be673a56128cc1e1b3c76588001a8c1b18/transpiler.js#L60
归档时间: |
|
查看次数: |
11067 次 |
最近记录: |