-
-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathuseJavascript.ts
30 lines (28 loc) · 920 Bytes
/
useJavascript.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
import * as babel from "@babel/core";
// @ts-expect-error These modules don't have types
import babelPluginSyntaxJSX from "@babel/plugin-syntax-jsx";
// @ts-expect-error These modules don't have types
import babelPresetTypeScript from "@babel/preset-typescript";
import prettier from "prettier";
export function transpile(
tsx: string,
options: {
cwd?: string;
filename?: string;
} = {}
): string {
let mjs = babel.transformSync(tsx, {
compact: false,
cwd: options.cwd,
filename: options.filename,
plugins: [babelPluginSyntaxJSX],
presets: [[babelPresetTypeScript, { jsx: "preserve" }]],
retainLines: true,
});
if (!mjs || !mjs.code) throw new Error("Could not parse TypeScript");
/**
* Babel's `compact` and `retainLines` options are both bad at formatting code.
* Use Prettier for nicer formatting.
*/
return prettier.format(mjs.code, { parser: "babel" });
}