mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
In 1.4.0 we can use the TypeScript API directly to preprocess our files. This lets us get rid of a dependency. https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API We can also use this to provide our default libraries so that we don't need to keep the references in the test file.
68 lines
1.8 KiB
JavaScript
68 lines
1.8 KiB
JavaScript
'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)
|
|
};
|
|
};
|