[Babel] Refactor compilation checks into a separate function
Sathya Gunasekaran committed
Mar 20, 2023 at 17:42 UTC
ff571d8d85adf6f26018686a9bd4a4c651f6430c
1 file changed
+25
-10
compiler/forget/src/Babel/BabelPlugin.ts
+25
-10
@@ -43,16 +43,6 @@ export default function ReactForgetBabelPlugin(
43
fn: BabelCore.NodePath<t.FunctionDeclaration>,
44
pass: BabelPluginPass
45
): void {
46
- if (pass.opts.enableOnlyOnUseForgetDirective) {
47
- if (!hasUseForgetDirective(fn.node.body.directives)) {
48
- return;
49
- }
50
- }
51
-
52
- if (fn.scope.getProgramParent() !== fn.scope.parent) {
53
- return;
54
- }
55
-
46
hasForgetCompiledCode = true;
47
const compiled = compile(fn, pass.opts.environment);
48
@@ -84,6 +74,10 @@ export default function ReactForgetBabelPlugin(
74
fn: BabelCore.NodePath<t.FunctionDeclaration>,
75
pass: BabelPluginPass
76
): void {
77
+ if (!shouldCompile(fn, pass)) {
78
+ return;
79
+ }
80
+
81
visitFn(fn, pass);
82
},
83
};
@@ -120,6 +114,27 @@ export default function ReactForgetBabelPlugin(
114
};
115
}
116
117
+function shouldCompile(
118
+ fn: BabelCore.NodePath<t.FunctionDeclaration | t.ArrowFunctionExpression>,
119
+ pass: BabelPluginPass
120
+): boolean {
121
+ if (pass.opts.enableOnlyOnUseForgetDirective) {
122
+ const body = fn.get("body");
123
+ if (!body.isBlockStatement()) {
124
+ return false;
125
+ }
126
+ if (!hasUseForgetDirective(body.node.directives)) {
127
+ return false;
128
+ }
129
+ }
130
+
131
+ if (fn.scope.getProgramParent() !== fn.scope.parent) {
132
+ return false;
133
+ }
134
+
135
+ return true;
136
+}
137
+
138
function buildGatingTest(
139
uncompiled: BabelCore.NodePath<t.FunctionDeclaration>,
140
compiled: t.Identifier,