forked from alangpierce/sucrase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.ts
84 lines (72 loc) · 2.31 KB
/
register.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
83
84
import * as pirates from "@astra-mod/pirates";
import {Options, transform} from "./index";
export interface HookOptions {
matcher?: (code: string) => boolean;
ignoreNodeModules?: boolean;
preHook?: (filename: string) => string;
}
export type RevertFunction = () => void;
export function addHook(
extension: string,
options: Options,
hookOptions?: HookOptions,
): RevertFunction {
return pirates.addHook(
(code: string, filePath: string): string => {
const {code: transformedCode, sourceMap} = transform(code, {
...options,
sourceMapOptions: {compiledFilename: filePath},
filePath,
});
const mapBase64 = Buffer.from(JSON.stringify(sourceMap)).toString("base64");
const suffix = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${mapBase64}`;
return `${transformedCode}\n${suffix}`;
},
{...hookOptions, exts: [extension]},
);
}
export function registerJS(hookOptions?: HookOptions): RevertFunction {
return addHook(".js", {transforms: ["imports", "flow", "jsx"]}, hookOptions);
}
export function registerJSX(hookOptions?: HookOptions): RevertFunction {
return addHook(".jsx", {transforms: ["imports", "flow", "jsx"]}, hookOptions);
}
export function registerTS(hookOptions?: HookOptions): RevertFunction {
return addHook(".ts", {transforms: ["imports", "typescript"]}, hookOptions);
}
export function registerTSX(hookOptions?: HookOptions): RevertFunction {
return addHook(".tsx", {transforms: ["imports", "typescript", "jsx"]}, hookOptions);
}
export function registerTSLegacyModuleInterop(hookOptions?: HookOptions): RevertFunction {
return addHook(
".ts",
{
transforms: ["imports", "typescript"],
enableLegacyTypeScriptModuleInterop: true,
},
hookOptions,
);
}
export function registerTSXLegacyModuleInterop(hookOptions?: HookOptions): RevertFunction {
return addHook(
".tsx",
{
transforms: ["imports", "typescript", "jsx"],
enableLegacyTypeScriptModuleInterop: true,
},
hookOptions,
);
}
export function registerAll(hookOptions?: HookOptions): RevertFunction {
const reverts = [
registerJS(hookOptions),
registerJSX(hookOptions),
registerTS(hookOptions),
registerTSX(hookOptions),
];
return () => {
for (const fn of reverts) {
fn();
}
};
}