如何使用createProgram从ts源代码生成js文件?

时间:2019-01-02 05:51:34

标签: typescript

我想从ts代码生成js代码。我知道'transpileModule'可以做到这一点。但是我想在代码中获取语义错误。因此,也许我将使用“ createProgram” API来做到这一点。但是我发现只能从中获取清除代码。

type File = { fileName: string, content: string, sourceFile?: ts.SourceFile }

function createProgram1(code: string) {
    const options = {
        module: ts.ModuleKind.CommonJS,
        target: ts.ScriptTarget.ES2015,
        strict: true,
        suppressOutputPathCheck: false,
        // noEmitOnError: true
    };
    const file: File = {fileName: 'test', content: code};

    const compilerHost = ts.createCompilerHost(options);
    compilerHost.getSourceFile = (fileName: string): ts.SourceFile | undefined => {
        file.sourceFile = file.sourceFile || ts.createSourceFile(fileName, file.content, ts.ScriptTarget.ES2015, true);
        console.log('sourceFile =====> ', file.sourceFile);
        return file.sourceFile;
    };
    compilerHost.writeFile = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: any[]): void => {
        console.log('writeFile =====> fileName: ', fileName, ', data: ', data);
    };

    const program = ts.createProgram([file.fileName], options, compilerHost);

    program.getTypeChecker();
    let emitResult = program.emit(
        file.sourceFile,
        (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: any[]): void => {
            console.log('emit =====> fileName: ', fileName, ', data: ', data);
        },
        undefined,
        true
    );

    // printError(program.getGlobalDiagnostics());
    // printError(program.getOptionsDiagnostics());
    // printError(program.getDeclarationDiagnostics());
    printError(program.getSemanticDiagnostics());
    printError(program.getSyntacticDiagnostics());

    console.log(`emitResult: `, emitResult);
}

function printError(diagnostics: ts.Diagnostic[]) {
    if (diagnostics == undefined || diagnostics == null) return;

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

createProgram(`let test: string = 'aa';`);

0 个答案:

没有答案