-
Notifications
You must be signed in to change notification settings - Fork 418
Expand file tree
/
Copy pathbubble-function-declaration.ts
More file actions
33 lines (30 loc) · 1.05 KB
/
bubble-function-declaration.ts
File metadata and controls
33 lines (30 loc) · 1.05 KB
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
import type * as babel from "@babel/core";
import * as t from "@babel/types";
export function bubbleFunctionDeclaration(path: babel.NodePath<t.FunctionDeclaration>): void {
const decl = path.node;
// Check if declaration is FunctionDeclaration
if (decl.id) {
const block = (path.findParent(current => current.isBlockStatement()) ||
path.scope.getProgramParent().path) as babel.NodePath<t.BlockStatement>;
if (path.parentPath.isExportNamedDeclaration()) {
path.parentPath.replaceWith(
t.exportNamedDeclaration(undefined, [t.exportSpecifier(decl.id, decl.id)]),
);
} else if (path.parentPath.isExportDefaultDeclaration()) {
path.replaceWith(decl.id);
} else {
path.remove();
}
const [tmp] = block.unshiftContainer(
"body",
t.variableDeclaration("const", [
t.variableDeclarator(
decl.id,
t.functionExpression(decl.id, decl.params, decl.body, decl.generator, decl.async),
),
]),
);
block.scope.registerDeclaration(tmp);
tmp.skip();
}
}