-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
parse_script.ts
49 lines (49 loc) · 1.35 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
47
48
49
import {Opts, transformWithTs} from '@formatjs/ts-transformer'
import ts from 'typescript'
import {debug} from './console_utils'
/**
* 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 {
debug('Using TS compiler to process file', fn)
output = ts.transpileModule(source, {
compilerOptions: {
allowJs: true,
target: ts.ScriptTarget.ESNext,
noEmit: true,
experimentalDecorators: true,
},
reportDiagnostics: true,
fileName: fn,
transformers: {
before: [transformWithTs(ts, opts)],
},
})
} catch (e) {
if (e instanceof Error) {
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,
})
)
}
}
}
}