-
Notifications
You must be signed in to change notification settings - Fork 2
/
compile.ts
55 lines (45 loc) · 1.8 KB
/
compile.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import * as ts from "typescript";
import * as fs from "fs";
import * as path from "path";
function reportDiagnostics(diagnostics: ts.Diagnostic[]): void {
diagnostics.forEach(diagnostic => {
let message = "Error";
if (diagnostic.file) {
let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
message += ` ${diagnostic.file.fileName} (${line + 1},${character + 1})`;
}
message += ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
console.log(message);
});
}
function readConfigFile(configFileName: string) {
// Read config file
const configFileText = fs.readFileSync(configFileName).toString();
// Parse JSON, after removing comments. Just fancier JSON.parse
const result = ts.parseConfigFileTextToJson(configFileName, configFileText);
const configObject = result.config;
if (!configObject) {
reportDiagnostics([result.error]);
process.exit(1);;
}
// Extract config infromation
const configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, path.dirname(configFileName));
if (configParseResult.errors.length > 0) {
reportDiagnostics(configParseResult.errors);
process.exit(1);
}
return configParseResult;
}
function compile(configFileName: string): void {
// Extract configuration from config file
let config = readConfigFile(configFileName);
// Compile
let program = ts.createProgram(config.fileNames, config.options);
let emitResult = program.emit();
// Report errors
reportDiagnostics(ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics));
// Return code
let exitCode = emitResult.emitSkipped ? 1 : 0;
process.exit(exitCode);
}
compile(process.argv[2]);