简体   繁体   English

用于在不同目录中编译的 TypeScript API

[英]TypeScript API for compiling in a different directory

I have a typescript program that contains multiple .ts files.我有一个包含多个.ts文件的打字稿程序。 I want to compile those .ts to .js and place them in a different directory.我想将这些.ts编译为.js并将它们放在不同的目录中。

I'm inspired by the example from this page: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API我受到此页面示例的启发: 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);
}

Then I use outDir in compiler options object然后我在编译器选项对象中使用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
});

It works, however I'm curious if there's a different way to decide the location where to write the .js files that doesn't involve outDir property from compiler options.它有效,但是我很好奇是否有不同的方法来决定编写不涉及编译器选项中的outDir属性的.js文件的位置。

Note: I'm looking for an answer that uses the typescript api and not the command line tsc注意:我正在寻找使用 typescript api 而不是命令行tsc的答案

The second argument for emit() is writeFile?: WriteFileCallback . emit()的第二个参数是writeFile?: WriteFileCallback You can try to use it and implement writing files yourself in whatever way you need:您可以尝试使用它并以您需要的任何方式自己实现写入文件:

program.emit(undefined, yourOwnWriteFileFunction);

Also, according to comments and the code, ts.createProgram() accepts custom implementation for CompilerHost which also can override writeFile :此外,根据注释和代码, ts.createProgram()接受CompilerHost自定义实现,它也可以覆盖writeFile

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

Relevant part of Program interface Program界面相关部分

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;

Note that these parts of API are not documented on the TypeScript wiki, so if you decide to use them you should keep an eye on breaking API changes page .请注意,这些 API 部分未记录在 TypeScript wiki 中,因此如果您决定使用它们,则应密切关注API 更改页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM