-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
parse_script.ts
46 lines (45 loc) · 1.22 KB
/
parse_script.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
43
44
45
46
import {Opts, transform} from '@formatjs/ts-transformer';
import ts from 'typescript';
/**
* Invoid TypeScript module transpilation with our TS transformer
* @param opts Formatjs TS Transformer opt
* @param fn filename
*/
export function parseScript(opts: Opts, fn?: string) {
return (source: string) => {
let output;
try {
output = ts.transpileModule(source, {
compilerOptions: {
allowJs: true,
target: ts.ScriptTarget.ESNext,
noEmit: true,
experimentalDecorators: true,
},
reportDiagnostics: true,
fileName: fn,
transformers: {
before: [transform(opts)],
},
});
} catch (e) {
e.message = `Error processing file ${fn}
${e.message || ''}`;
throw e;
}
if (output.diagnostics) {
const errs = output.diagnostics.filter(
d => d.category === ts.DiagnosticCategory.Error
);
if (errs.length) {
throw new Error(
ts.formatDiagnosticsWithColorAndContext(errs, {
getCanonicalFileName: fileName => fileName,
getCurrentDirectory: () => process.cwd(),
getNewLine: () => ts.sys.newLine,
})
);
}
}
};
}