-
Notifications
You must be signed in to change notification settings - Fork 56
/
babel.ts
82 lines (78 loc) · 2.76 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import type {
TransformOptions as BabelTransformOptions,
PluginItem,
} from "@babel/core";
import { transformSync } from "@babel/core";
import proposalDecoratorsPlugin from "@babel/plugin-proposal-decorators";
import syntaxClassPropertiesPlugin from "@babel/plugin-syntax-class-properties";
import syntaxImportAssertionsPlugin from "@babel/plugin-syntax-import-assertions";
import transformExportNamespaceFromPlugin from "@babel/plugin-transform-export-namespace-from";
import transformTypeScriptPlugin from "@babel/plugin-transform-typescript";
import parameterDecoratorPlugin from "babel-plugin-parameter-decorator";
import transformTypeScriptMetaPlugin from "babel-plugin-transform-typescript-metadata";
import { TransformImportMetaPlugin } from "./plugins/babel-plugin-transform-import-meta";
import { importMetaEnvPlugin } from "./plugins/import-meta-env";
import transformModulesPlugin from "./plugins/transform-module";
import type { TransformOptions, TransformResult } from "./types";
export default function transform(opts: TransformOptions): TransformResult {
const _opts: BabelTransformOptions & { plugins: PluginItem[] } = {
babelrc: false,
configFile: false,
compact: false,
retainLines:
typeof opts.retainLines === "boolean" ? opts.retainLines : true,
filename: "",
cwd: "/",
...opts.babel,
plugins: [
[
transformModulesPlugin,
{
allowTopLevelThis: true,
noInterop: !opts.interopDefault,
async: opts.async,
},
],
[TransformImportMetaPlugin, { filename: opts.filename }],
[syntaxClassPropertiesPlugin],
[transformExportNamespaceFromPlugin],
[importMetaEnvPlugin],
],
};
if (opts.ts) {
_opts.plugins.push([
transformTypeScriptPlugin,
{ allowDeclareFields: true },
]);
// `unshift` because these plugin must come before `@babel/plugin-syntax-class-properties`
_opts.plugins.unshift(
[transformTypeScriptMetaPlugin],
[proposalDecoratorsPlugin, { legacy: true }],
);
_opts.plugins.push(parameterDecoratorPlugin);
_opts.plugins.push(syntaxImportAssertionsPlugin);
}
if (opts.babel && Array.isArray(opts.babel.plugins)) {
_opts.plugins?.push(...opts.babel.plugins);
}
try {
return {
code: transformSync(opts.source, _opts)?.code || "",
};
} catch (error: any) {
return {
error,
code:
"exports.__JITI_ERROR__ = " +
JSON.stringify({
filename: opts.filename,
line: error.loc?.line || 0,
column: error.loc?.column || 0,
code: error.code
?.replace("BABEL_", "")
.replace("PARSE_ERROR", "ParseError"),
message: error.message?.replace("/: ", "").replace(/\(.+\)\s*$/, ""),
}),
};
}
}