forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPISample_transform.ts
More file actions
68 lines (56 loc) · 2.34 KB
/
Copy pathAPISample_transform.ts
File metadata and controls
68 lines (56 loc) · 2.34 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
// @module: commonjs
// @includebuiltfile: typescript.d.ts
// @stripInternal:true
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-simple-transform-function
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
declare var fs: any;
declare var path: any;
declare var os: any;
import ts = require("typescript");
function transform(contents: string, compilerOptions: ts.CompilerOptions = {}) {
// Sources
var files = {
"file.ts": contents,
"lib.d.ts": fs.readFileSync(ts.getDefaultLibFilePath(compilerOptions)).toString()
};
// Generated outputs
var outputs = [];
// Create a compilerHost object to allow the compiler to read and write files
var compilerHost = {
getSourceFile: (fileName, target) => {
return files[fileName] !== undefined ?
ts.createSourceFile(fileName, files[fileName], target) : undefined;
},
writeFile: (name, text, writeByteOrderMark) => {
outputs.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
},
getDefaultLibFileName: () => "lib.d.ts",
useCaseSensitiveFileNames: () => false,
getCanonicalFileName: (fileName) => fileName,
getCurrentDirectory: () => "",
getNewLine: () => "\n"
};
// Create a program from inputs
var program = ts.createProgram(["file.ts"], compilerOptions, compilerHost);
// Query for early errors
var errors = ts.getPreEmitDiagnostics(program);
var emitResult = program.emit();
errors = errors.concat(emitResult.diagnostics);
return {
outputs: outputs,
errors: errors.map(function (e) {
return e.file.fileName + "(" + e.file.getLineAndCharacterFromPosition(e.start).line + "): "
+ ts.flattenDiagnosticMessageText(e.messageText, os.EOL);
})
};
}
// Calling our transform function using a simple TypeScript variable declarations,
// and loading the default library like:
var source = "var x: number = 'string'";
var result = transform(source);
console.log(JSON.stringify(result));