From 3cd3735515e5efe8f0e2a73e3e241d436cd7aa41 Mon Sep 17 00:00:00 2001 From: Mike Vitousek Date: Tue, 11 Jun 2024 14:08:21 -0700 Subject: [PATCH] [compiler] Option to only compile component syntax Summary: Projects which have heavily adopted Flow component syntax may wish to enable the compiler only for components and hooks that use the syntax, rather than trying to guess which functions are components and hooks. This provides that option. ghstack-source-id: 579ac9f0fa01d8cdb6a0b8f9923906a0b37662f3 Pull Request resolved: https://github.com/facebook/react/pull/29864 --- .../src/Entrypoint/Options.ts | 2 ++ .../src/Entrypoint/Program.ts | 27 +++++++++++-------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts index 70f32c85b2..87cc05e462 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts @@ -131,6 +131,8 @@ const CompilationModeSchema = z.enum([ * This is the default mode */ "infer", + // Compile only components using Flow component syntax and hooks using hook syntax. + "syntax", // Compile only functions which are explicitly annotated with "use forget" "annotation", // Compile all top-level functions diff --git a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts index b47795106b..085ac44f49 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts @@ -499,23 +499,28 @@ function getReactFunctionType( return getComponentOrHookLike(fn, hookPattern) ?? "Other"; } } + + // Component and hook declarations are known components/hooks + let componentSyntaxType: ReactFunctionType | null = null; + if (fn.isFunctionDeclaration()) { + if (isComponentDeclaration(fn.node)) { + componentSyntaxType = "Component"; + } else if (isHookDeclaration(fn.node)) { + componentSyntaxType = "Hook"; + } + } + switch (pass.opts.compilationMode) { case "annotation": { // opt-ins are checked above return null; } case "infer": { - // Component and hook declarations are known components/hooks - if (fn.isFunctionDeclaration()) { - if (isComponentDeclaration(fn.node)) { - return "Component"; - } else if (isHookDeclaration(fn.node)) { - return "Hook"; - } - } - - // Otherwise check if this is a component or hook-like function - return getComponentOrHookLike(fn, hookPattern); + // Check if this is a component or hook-like function + return componentSyntaxType ?? getComponentOrHookLike(fn, hookPattern); + } + case "syntax": { + return componentSyntaxType; } case "all": { // Compile only top level functions