-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.ts
More file actions
73 lines (63 loc) · 2.04 KB
/
compile.ts
File metadata and controls
73 lines (63 loc) · 2.04 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Compile `ts` files using transformer
// Originally comes from https://github.com/longlho/ts-transform-img
import ts from "typescript";
import fs from "fs";
import { createTransformerFactory } from "./src/transformer";
function formatDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic>) {
const messages: Array<string> = [];
for (const diagnostic of diagnostics) {
let signature: string;
if (diagnostic.file) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
diagnostic.start!
);
signature = `${diagnostic.file!.fileName} (${line + 1},${character + 1})`;
} else {
signature = "(unknown)";
}
const message = ts.flattenDiagnosticMessageText(
diagnostic.messageText,
"\n"
);
messages.push(`[compile.ts] ${signature}: ${message}`);
}
return messages;
}
function readTsConfig(filename = "./tsconfig.json"): ts.CompilerOptions {
const tsConfig = ts.readConfigFile(filename, path =>
fs.readFileSync(path).toString()
);
if (tsConfig.error) {
throw new Error(formatDiagnostics([tsConfig.error]).join("\n"));
}
const basePath = __dirname;
const result = ts.convertCompilerOptionsFromJson(
tsConfig.config.compilerOptions,
basePath,
filename
);
if (result.errors.length > 0) {
throw new Error(formatDiagnostics(result.errors).join("\n"));
}
return result.options;
}
export function compile(
files: ReadonlyArray<string>,
options: ts.CompilerOptions = readTsConfig()
) {
const compilerHost = ts.createCompilerHost(options);
const program = ts.createProgram(files, options, compilerHost);
const emitResult = program.emit(undefined, undefined, undefined, undefined, {
before: [createTransformerFactory(program)]
});
const diagnostics = ts
.getPreEmitDiagnostics(program)
.concat(emitResult.diagnostics);
if (diagnostics.length > 0) {
throw new Error(formatDiagnostics(diagnostics).join("\n"));
}
}
if (require.main === module) {
const [_nodejs, _compiler_ts, ...args] = process.argv;
compile(args);
}