如何在ClearScript V8中调用typescript.js设置TypeScript编译目标版本
ClearScript V8中配置TypeScript转译目标为ES2021的方法
你加载的typescriptServices.js暴露的全局ts对象的转译方法本身支持直接传入编译配置,不需要依赖tsconfig文件,操作逻辑如下:
- 调用转译方法
ts.transpile()时,第二个参数即为编译选项对象,直接指定target字段为ts.ScriptTarget.ES2021即可覆盖默认的ES3配置 - 其余编译配置(如模块规范、严格模式等)也可在该对象中直接定义,字段规则和tsconfig配置项完全对应
示例代码
场景1:在V8上下文的JS代码中直接调用
// 待转译的TypeScript代码 const sourceTsCode = `const num: number = 123; console.log(num ?? 0);`; // 传入配置执行转译 const compiledJsCode = ts.transpile(sourceTsCode, { target: ts.ScriptTarget.ES2021, // 可按需添加其他配置 module: ts.ModuleKind.ESNext, strict: true });
场景2:在C#层通过ClearScript接口调用
// 已经加载完typescriptServices.js的V8引擎实例 var v8Engine = new V8ScriptEngine(); // ... 此处省略加载typescriptServices.js的代码 // 获取全局ts对象 dynamic ts = v8Engine.Script.ts; // 构造编译配置对象 dynamic compileOpts = v8Engine.Evaluate(@" ({ target: ts.ScriptTarget.ES2021, module: ts.ModuleKind.ESNext }) "); // 执行转译 string tsCode = "const num: number = 123; console.log(num ?? 0);"; string jsResult = ts.transpile(tsCode, compileOpts);
注意事项
如果你加载的TypeScript版本较旧,没有内置ES2021对应的枚举值,可以直接传入数字13代替ts.ScriptTarget.ES2021。你也可以直接打印ts.ScriptTarget对象,确认你当前使用的TypeScript版本中ES2021对应的枚举数值。
内容的提问来源于stack exchange,提问作者gjvdkamp
相关产品推荐
相关产品推荐

