forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathts-preprocessor.js
73 lines (65 loc) · 1.8 KB
/
ts-preprocessor.js
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
'use strict';
var fs = require('fs');
var path = require('path');
var ts = require('typescript');
var tsOptions = {module: 'commonjs'};
function formatErrorMessage(error) {
return (
error.file.filename + '(' +
error.file.getLineAndCharacterFromPosition(error.start).line +
'): ' +
error.messageText
);
}
function compile(defaultLib, content, contentFilename) {
var output = null;
var compilerHost = {
getSourceFile: function(filename, languageVersion) {
if (filename === contentFilename) {
return ts.createSourceFile(filename, content, 'ES5', '0');
}
return defaultLib;
},
writeFile: function(name, text, writeByteOrderMark) {
if (output === null) {
output = text;
} else {
throw new Error('Expected only one dependency.');
}
},
getCanonicalFileName: function(filename) {
return filename;
},
getCurrentDirectory: function() {
return '';
},
getNewLine: function() {
return '\n';
}
};
var program = ts.createProgram([contentFilename], tsOptions, compilerHost);
var errors = program.getDiagnostics();
if (!errors.length) {
var checker = program.getTypeChecker(true);
errors = checker.getDiagnostics();
checker.emitFiles();
}
if (errors.length) {
throw new Error(errors.map(formatErrorMessage).join('\n'));
}
return output;
}
module.exports = function(defaultLibs) {
var defaultLibSource = fs.readFileSync(
path.join(path.dirname(require.resolve('typescript')), 'lib.d.ts')
);
for (var i = 0; i < defaultLibs.length; i++) {
defaultLibSource += '\n' + fs.readFileSync(defaultLibs[i]);
}
var defaultLibSourceFile = ts.createSourceFile(
'lib.d.ts', defaultLibSource, 'ES5'
);
return {
compile: compile.bind(null, defaultLibSourceFile)
};
};