* 编译Ts代码 * * tsc的api实现
()
| 59 | * tsc的api实现 |
| 60 | */ |
| 61 | function compileTsCode(): Promise<void> { |
| 62 | function compile( |
| 63 | fileNames: string[], |
| 64 | options: ts.CompilerOptions |
| 65 | ): Promise<void> { |
| 66 | return new Promise<void>((resolve, reject) => { |
| 67 | const program = ts.createProgram(fileNames, options); |
| 68 | const emitResult = program.emit(); |
| 69 | |
| 70 | const allDiagnostics = ts |
| 71 | .getPreEmitDiagnostics(program) |
| 72 | .concat(emitResult.diagnostics); |
| 73 | |
| 74 | allDiagnostics.forEach((diagnostic) => { |
| 75 | if (diagnostic.file) { |
| 76 | const { line, character } = ts.getLineAndCharacterOfPosition( |
| 77 | diagnostic.file, |
| 78 | diagnostic.start! |
| 79 | ); |
| 80 | const message = ts.flattenDiagnosticMessageText( |
| 81 | diagnostic.messageText, |
| 82 | '\n' |
| 83 | ); |
| 84 | console.log( |
| 85 | `${diagnostic.file.fileName} (${line + 1},${ |
| 86 | character + 1 |
| 87 | }): ${message}` |
| 88 | ); |
| 89 | } else { |
| 90 | console.log( |
| 91 | ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n') |
| 92 | ); |
| 93 | } |
| 94 | }); |
| 95 | |
| 96 | const exitCode = emitResult.emitSkipped ? 1 : 0; |
| 97 | if (exitCode === 0) { |
| 98 | resolve(); |
| 99 | } else { |
| 100 | reject(); |
| 101 | } |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | const configPath = ts.findConfigFile( |
| 106 | process.cwd() /*searchPath*/, |
| 107 | ts.sys.fileExists, |
| 108 | 'tsconfig.json' |
| 109 | ); |
| 110 | const configFile = ts.readJsonConfigFile(configPath, ts.sys.readFile); |
| 111 | const { fileNames, options } = ts.parseJsonSourceFileConfigFileContent( |
| 112 | configFile, |
| 113 | ts.sys, |
| 114 | process.cwd() |
| 115 | ); |
| 116 | |
| 117 | return compile(fileNames, options); |
| 118 | } |
no test coverage detected