-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompiler.ts
105 lines (93 loc) · 2.67 KB
/
Compiler.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import * as ts from "typescript";
import Transformers from "./Transformers/Index";
import PostCSS from "./CSSCompiler";
import { writeFileSync } from "fs";
import { join } from "path";
import CSS from "./CSSCompiler";
const formatHost: ts.FormatDiagnosticsHost = {
getCanonicalFileName: path => path,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => ts.sys.newLine
};
function mergeTransformers(
t1: ts.CustomTransformers,
t2: ts.CustomTransformers
) {
if (!t2) return t1;
return {
after: t1.after ? t1.after.concat(t2.after) : t2.after,
before: t1.before ? t1.before.concat(t2.before) : t2.before,
afterDeclarations: t1.afterDeclarations
? t1.afterDeclarations.concat(t2.afterDeclarations)
: t2.afterDeclarations
} as ts.CustomTransformers;
}
declare global {
namespace NodeJS {
interface Global {
CurrentProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram;
}
}
}
function watchMain() {
const configPath = ts.findConfigFile(".", ts.sys.fileExists, "tsconfig.json");
if (!configPath) {
throw new Error("Could not find a valid 'tsconfig.json'.");
}
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
const host = ts.createWatchCompilerHost(
configPath,
{},
ts.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
);
const origPostProgramCreate = host.afterProgramCreate;
host.afterProgramCreate = program => {
const org = program.emit;
global.CurrentProgram = program;
program.emit = function(
targetSourceFile?: ts.SourceFile,
writeFile?: ts.WriteFileCallback,
cancellationToken?: ts.CancellationToken,
emitOnlyDtsFiles?: boolean,
customTransformers?: ts.CustomTransformers
) {
const R = org(
targetSourceFile,
writeFile,
cancellationToken,
emitOnlyDtsFiles,
mergeTransformers(Transformers, customTransformers)
);
CSS.Processor.process(Object.values(PostCSS.Styles).join("\n"), {
from: undefined
}).then(x =>
writeFileSync(join(program.getCompilerOptions().outDir, "Style.css"), x.css)
);
return R;
};
origPostProgramCreate!(program);
try {
} catch (ex) {
console.error("[TS]", ex);
}
};
ts.createWatchProgram(host).getProgram();
}
function reportDiagnostic(diagnostic: ts.Diagnostic) {
console.error(
"Error",
diagnostic.code,
":",
ts.flattenDiagnosticMessageText(
diagnostic.messageText,
formatHost.getNewLine()
)
);
}
function reportWatchStatusChanged(diagnostic: ts.Diagnostic) {
console.info(ts.formatDiagnostic(diagnostic, formatHost));
}
watchMain();