forked from lyft/react-javascript-to-typescript-transform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.ts
42 lines (34 loc) · 1.45 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
import * as ts from 'typescript';
import * as chalk from 'chalk';
import { TransformFactoryFactory } from '.';
/**
* Compile and return result TypeScript
* @param filePath Path to file to compile
*/
export function compile(filePath: string, factoryFactories: TransformFactoryFactory[]) {
const compilerOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES2017,
module: ts.ModuleKind.ES2015,
};
const program = ts.createProgram([filePath], compilerOptions);
const sourceFiles = program.getSourceFiles().filter(sf => !sf.isDeclarationFile);
const typeChecker = program.getTypeChecker();
const result = ts.transform(
sourceFiles,
factoryFactories.map(factoryFactory => factoryFactory(typeChecker), compilerOptions),
);
if (result.diagnostics && result.diagnostics.length) {
console.log(chalk.yellow(`
======================= Diagnostics for ${filePath} =======================
`));
for (const diag of result.diagnostics) {
if (diag.file && diag.start) {
const pos = diag.file.getLineAndCharacterOfPosition(diag.start);
console.log(`(${pos.line}, ${pos.character}) ${diag.messageText}`)
}
}
}
const printer = ts.createPrinter()
// TODO: fix the index 0 access... What if program have multiple source files?
return printer.printNode(ts.EmitHint.SourceFile, result.transformed[0], sourceFiles[0]);
}