forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypescript.js
74 lines (69 loc) · 2.58 KB
/
typescript.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
74
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const colors = require('ansi-colors');
const fs = require('fs-extra');
const log = require('fancy-log');
const path = require('path');
const ts = require('typescript');
const tsickle = require('tsickle');
/**
* Given a file path `foo/bar.js`, transpiles the TypeScript entry point of
* the same name `foo/bar.ts` and all direct and indirect TypeScript imports.
*
* @param {string} srcDir
* @param {string} srcFilename
*/
exports.transpileTs = function(srcDir, srcFilename) {
const tsEntry = path.join(srcDir, srcFilename).replace(/\.js$/, '.ts');
const tsConfig = ts.convertCompilerOptionsFromJson({
'module': 'ES6',
'target': 'ES6',
}, srcDir);
const tsOptions = tsConfig.options;
if (tsConfig.errors.length) {
log(colors.red('TSickle:'), tsickle.formatDiagnostics(tsConfig.errors));
}
const compilerHost = ts.createCompilerHost(tsOptions);
const program = ts.createProgram([tsEntry], tsOptions, compilerHost);
// TODO(choumx): This was partially copy-pasta'd from tsickle. Add a default
// to tsickle so this can be an optional param.
const pathToModuleName = (context, fileName) => {
fileName = fileName.replace(/\.js$/, '');
if (fileName[0] === '.') {
// './foo' or '../foo'.
// Resolve the path against the dirname of the current module.
fileName = path.join(path.dirname(context), fileName);
}
return fileName;
};
const transformerHost = {
host: compilerHost,
options: tsOptions,
pathToModuleName,
shouldSkipTsickleProcessing: () => false,
transformTypesToClosure: true,
};
const emitResult = tsickle.emitWithTsickle(program, transformerHost,
compilerHost, tsOptions, undefined, (filePath, contents) => {
fs.writeFileSync(filePath, contents, {encoding: 'utf-8'});
});
const diagnostics =
ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
if (diagnostics.length) {
log(colors.red('TSickle:'), tsickle.formatDiagnostics(diagnostics));
}
};