禁用默认的打字稿转换器

sup*_*key 0 typescript typescript-compiler-api

我想使用 typescript 转换器 api 编写一个自定义转换器,输出 typescript 而不是 javascript。为了实现这一点,我需要禁用默认转换器(typescript \xe2\x86\x92 ecma2017 \xe2\x86\x92 ecma2016 \xe2\x86\x92 ...)。

\n\n

这可能吗?我更喜欢直接使用tsc,但如果我必须手动使用编译器 api 也没关系。

\n

Dav*_*ret 5

没有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));
Run Code Online (Sandbox Code Playgroud)