用于在其他目录中编译的TypeScript API

时间:2019-01-21 21:32:06

标签: node.js typescript

我有一个打字稿程序,其中包含多个.ts文件。 我想将这些.ts编译为.js并将它们放置在其他目录中。

我受到此页面中示例的启发:https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API

function compile(fileNames, options) {
    let program = ts.createProgram(fileNames, options);
    let emitResult = program.emit();

    let allDiagnostics = ts
        .getPreEmitDiagnostics(program)
        .concat(emitResult.diagnostics);

    allDiagnostics.forEach(diagnostic => {
        if (diagnostic.file) {
            let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(
                diagnostic.start
            );
            let message = ts.flattenDiagnosticMessageText(
                diagnostic.messageText,
                "\n"
            );
            console.log(
                `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
            );
        } else {
            console.log(
                `${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`
            );
        }
    });

    let exitCode = emitResult.emitSkipped ? 1 : 0;
    console.log(`Process exiting with code '${exitCode}'.`);
    process.exit(exitCode);
}

然后我在编译器选项对象中使用outDir

compile(["test.ts"], {
    noEmitOnError: false,
    noImplicitAny: false,
    target: ts.ScriptTarget.ES5,
    module: ts.ModuleKind.ESNext,
    outDir: "output" // files are placed in a directory called output
});

它可以工作,但是我很好奇是否有另一种方法可以确定写入.js文件的位置,该位置不涉及编译器选项中的outDir属性。

注意:我正在寻找一个使用打字稿api而不是命令行tsc

的答案

1 个答案:

答案 0 :(得分:1)

emit()的第二个参数是writeFile?: WriteFileCallback。您可以尝试使用它并以自己需要的方式实现自己编写文件:

program.emit(undefined, yourOwnWriteFileFunction);

此外,根据注释和代码,ts.createProgram()接受CompilerHost的自定义实现,该实现也可以覆盖writeFile

export interface CompilerHost extends ModuleResolutionHost {
    ....
    writeFile: WriteFileCallback;

Relevant part of Program interface

export interface Program extends ScriptReferenceHost {

    /**
     * Emits the JavaScript and declaration files.  If targetSourceFile is not specified, then
     * the JavaScript and declaration files will be produced for all the files in this program.
     * If targetSourceFile is specified, then only the JavaScript and declaration for that
     * specific file will be generated.
     *
     * If writeFile is not specified then the writeFile callback from the compiler host will be
     * used for writing the JavaScript and declaration files.  Otherwise, the writeFile parameter
     * will be invoked when writing the JavaScript and declaration files.
     */
    emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult;

请注意,API的这些部分没有记录在TypeScript Wiki上,因此,如果您决定使用它们,则应注意breaking API changes page