【发布时间】:2019-04-04 22:03:46
【问题描述】:
我想使用输出 typescript 而不是 javascript 的 typescript 转换器 api 编写一个自定义转译器。为此,我需要禁用默认转换器(typescript → ecma2017 → ecma2016 → ...)。
这可能吗?我更喜欢直接使用tsc,但如果我必须手动使用编译器api也可以。
【问题讨论】:
标签: typescript typescript-compiler-api
我想使用输出 typescript 而不是 javascript 的 typescript 转换器 api 编写一个自定义转译器。为此,我需要禁用默认转换器(typescript → ecma2017 → ecma2016 → ...)。
这可能吗?我更喜欢直接使用tsc,但如果我必须手动使用编译器api也可以。
【问题讨论】:
标签: typescript typescript-compiler-api
没有ts.ScriptTarget.TypeScript,因此您需要使用编译器 API。
这是基本想法(未经测试,但应该可以帮助您开始):
import * as ts from "typescript";
// setup
const printer = ts.createPrinter();
const sourceFiles: ts.SourceFile[] = ...;
const transformerFactory: ts.TransformerFactory<ts.SourceFile> = ...;
// transform the source files
const transformationResult = ts.transform(sourceFiles, [transformerFactory]);
// log the diagnostics if they exist
if (transformationResult.diagnostics) {
// output diagnostics (ts.formatDiagnosticsWithColorAndContext is nice to use)
}
// print the transformed ASTs and write the result out to files
// note: replace fs.writeFile with something that actually works
const fileWrites = transformationResult.transformed
.map(file => fs.writeFile(file.fileName, printer.printFile(file));
Promise.all(fileWrites)
.then(() => console.log("finished"))
.catch(err => console.error(err));
【讨论】: