-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathbabel.ts
53 lines (48 loc) · 1.85 KB
/
babel.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
50
51
52
53
import { transformSync, TransformOptions as BabelTransformOptions } from '@babel/core'
import { TransformOptions, TRANSFORM_RESULT } from './types'
export default function transform (opts: TransformOptions): TRANSFORM_RESULT {
const _opts: BabelTransformOptions = {
babelrc: false,
configFile: false,
compact: false,
retainLines: typeof opts.retainLines === 'boolean' ? opts.retainLines : true,
filename: '',
cwd: '/',
...opts.babel,
plugins: [
[require('@babel/plugin-transform-modules-commonjs'), { allowTopLevelThis: true }],
[require('babel-plugin-dynamic-import-node'), { noInterop: true }],
[require('babel-plugin-transform-import-meta')],
[require('@babel/plugin-syntax-class-properties')]
]
}
if (opts.ts) {
_opts.plugins!.push(require('@babel/plugin-transform-typescript'))
// `unshift` because this plugin must come before `@babel/plugin-syntax-class-properties`
_opts.plugins!.unshift([require('@babel/plugin-proposal-decorators'), { legacy: true }])
_opts.plugins!.push(require('babel-plugin-parameter-decorator'))
}
if (opts.legacy) {
_opts.plugins!.push(require('@babel/plugin-proposal-nullish-coalescing-operator'))
_opts.plugins!.push(require('@babel/plugin-proposal-optional-chaining'))
}
if (opts.babel && Array.isArray(opts.babel.plugins)) {
_opts.plugins?.push(...opts.babel.plugins)
}
try {
return {
code: transformSync(opts.source, _opts)?.code || ''
}
} catch (err) {
return {
error: err,
code: 'exports.__JITI_ERROR__ = ' + JSON.stringify({
filename: opts.filename,
line: err.loc?.line || 0,
column: err.loc?.column || 0,
code: err.code?.replace('BABEL_', '').replace('PARSE_ERROR', 'ParseError'),
message: err.message?.replace('/: ', '').replace(/\(.+\)\s*$/, '')
})
}
}
}