diff --git a/news/+window-libraries-dynamic-only.performance.md b/news/+window-libraries-dynamic-only.performance.md new file mode 100644 index 00000000000..76febacd4d7 --- /dev/null +++ b/news/+window-libraries-dynamic-only.performance.md @@ -0,0 +1 @@ +Apps that render no dynamic component no longer import whole libraries into the app root. A blank app ships about 70 KB less gzipped JavaScript, because `@radix-ui/themes` is tree-shaken to the components its pages use. Libraries the compiler registers on its own (a plugin's frontend dependencies, Radix Themes) are now exposed on `window.__reflex` only when a page evaluates a component held in state. A script that reads one of them from `window.__reflex` directly must register it with `bundle_library("")`, which always exposes it. diff --git a/packages/reflex-base/news/+bundle-library-exposure.docs.md b/packages/reflex-base/news/+bundle-library-exposure.docs.md new file mode 100644 index 00000000000..bbddfd62c0f --- /dev/null +++ b/packages/reflex-base/news/+bundle-library-exposure.docs.md @@ -0,0 +1 @@ +Document in `bundle_library` that libraries the compiler registers on its own are exposed on `window.__reflex` only when a page evaluates a dynamic component, while a library registered with `bundle_library` is always exposed. diff --git a/packages/reflex-base/src/reflex_base/components/dynamic.py b/packages/reflex-base/src/reflex_base/components/dynamic.py index a32e4cddff1..7ebfd89fe5d 100644 --- a/packages/reflex-base/src/reflex_base/components/dynamic.py +++ b/packages/reflex-base/src/reflex_base/components/dynamic.py @@ -97,6 +97,10 @@ def bundle_library(component: Union["Component", str]) -> None: state. Components present in the initial state have their imports bundled automatically. + Libraries the compiler registers on its own, such as a plugin's frontend + dependencies, are exposed on ``window.__reflex`` only when a page evaluates + a dynamic component. A library registered here is always exposed. + Args: component: A library name string or a prototype component instance to bundle. diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..80d6205c0b1 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -143,16 +143,24 @@ def _normalize_library_name(lib: str) -> str: ) -def _get_window_libraries() -> list[tuple[str, str]]: +def _get_window_libraries(*, implicit: bool = True) -> list[tuple[str, str]]: """Build distinct JavaScript aliases for bundled libraries and subpaths. + Args: + implicit: Whether to include the libraries the compiler registered for + dynamic components, beyond the defaults and the app's own + registrations. + Returns: Library aliases paired with their original module paths. """ + context = RegistrationContext.ensure_context() used_aliases: set[str] = set() window_libraries: list[tuple[str, str]] = [] for library in dict.fromkeys( - RegistrationContext.ensure_context().bundled_libraries + context.bundled_libraries + if implicit + else (*_default_bundled_libraries(), *context._explicit_bundled_libraries) ): base_alias = _normalize_library_name(library) alias = base_alias @@ -166,7 +174,10 @@ def _get_window_libraries() -> list[tuple[str, str]]: def _compile_app( - app_root: Component, hydrate_fallback_export: str | None = None + app_root: Component, + hydrate_fallback_export: str | None = None, + *, + dynamic_components: bool = True, ) -> str: """Compile the app template component. @@ -174,11 +185,14 @@ def _compile_app( app_root: The app root to compile. hydrate_fallback_export: The exported name of the hydrate-fallback memo component to re-export as ``HydrateFallback``, or None for no fallback. + dynamic_components: Whether the frontend evaluates dynamic components. + Without them, only the default libraries and the ones the app + registered with ``bundle_library`` are exposed on ``window.__reflex``. Returns: The compiled app. """ - window_libraries = _get_window_libraries() + window_libraries = _get_window_libraries(implicit=dynamic_components) lazy_window_libraries = [] if get_config().frontend_lazy_bundled_libraries: core_libraries = set(_default_bundled_libraries()) @@ -720,7 +734,10 @@ def compile_document_root( def compile_app_root( - app_root: Component, hydrate_fallback_export: str | None = None + app_root: Component, + hydrate_fallback_export: str | None = None, + *, + dynamic_components: bool = True, ) -> tuple[str, str]: """Compile the app root. @@ -728,6 +745,9 @@ def compile_app_root( app_root: The app root component to compile. hydrate_fallback_export: The exported name of the hydrate-fallback memo component to re-export as ``HydrateFallback``, or None for no fallback. + dynamic_components: Whether the frontend evaluates dynamic components. + Without them, only the default libraries and the ones the app + registered with ``bundle_library`` are exposed on ``window.__reflex``. Returns: The path and code of the compiled app wrapper. @@ -738,7 +758,9 @@ def compile_app_root( ) # Compile the document root. - code = _compile_app(app_root, hydrate_fallback_export) + code = _compile_app( + app_root, hydrate_fallback_export, dynamic_components=dynamic_components + ) return output_path, code @@ -1592,7 +1614,18 @@ def add_save_task( ]) progress.advance(task) - compile_results.append(compile_app_root(app_root, hydrate_fallback_export)) + # Only a module that imports the evaluator can read an optional library + # from window.__reflex, so the rest of the app need not carry them. + compile_results.append( + compile_app_root( + app_root, + hydrate_fallback_export, + dynamic_components=any( + import_var.tag == "evalReactComponent" + for import_var in all_imports.get(f"$/{constants.Dirs.STATE_PATH}", ()) + ), + ) + ) progress.advance(task) progress.stop() diff --git a/tests/integration/tests_playwright/test_radix_components.py b/tests/integration/tests_playwright/test_radix_components.py index 4203fa907fe..f4379a8d9b8 100644 --- a/tests/integration/tests_playwright/test_radix_components.py +++ b/tests/integration/tests_playwright/test_radix_components.py @@ -65,3 +65,20 @@ def test_progress_aria_value_updates(progress_app: AppHarness, page: Page) -> No page.get_by_role("button", name="Advance").click() expect(progressbar).to_have_attribute("aria-valuenow", "50") + + +def test_window_libraries_without_dynamic_components( + progress_app: AppHarness, page: Page +) -> None: + """An app that evaluates no dynamic component exposes only the default libraries.""" + assert progress_app.frontend_url is not None + + page.goto(progress_app.frontend_url) + page.wait_for_function("() => window.__reflex") + assert page.evaluate("() => Object.keys(window.__reflex)") == [ + "react", + "@emotion/react", + "$/utils/context", + "$/utils/context-registry", + "$/utils/state", + ] diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..27e2d56a3f4 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -772,6 +772,100 @@ def test_compile_app_root_can_defer_optional_window_libraries(mocker): assert "window.__reflex_load" in code +def test_get_window_libraries_can_leave_out_implicit_libraries(): + """Keep only the default and app-registered libraries when asked to.""" + with RegistrationContext(): + compiler._bundle_plugin_frontend_dependencies([rx.plugins.RadixThemesPlugin()]) + bundle_library("d3-format@3.1.0") + + assert compiler._get_window_libraries() == [ + ("React", "react"), + ("emotion_react", "@emotion/react"), + ("utils_context", "$/utils/context"), + ("utils_context_registry", "$/utils/context-registry"), + ("utils_state", "$/utils/state"), + ("radix_ui_themes", "@radix-ui/themes"), + ("d3_format", "d3-format"), + ] + assert compiler._get_window_libraries(implicit=False) == [ + ("React", "react"), + ("emotion_react", "@emotion/react"), + ("utils_context", "$/utils/context"), + ("utils_context_registry", "$/utils/context-registry"), + ("utils_state", "$/utils/state"), + ("d3_format", "d3-format"), + ] + + +@pytest.mark.parametrize("lazy", [False, True]) +@pytest.mark.parametrize("dynamic", [False, True]) +def test_compile_app_bundles_implicit_libraries_only_for_dynamic_components( + lazy: bool, dynamic: bool, tmp_path: Path, monkeypatch, mocker: MockerFixture +): + """Expose Radix on window.__reflex only when a page evaluates a component. + + Args: + lazy: Whether optional bundled libraries load lazily. + dynamic: Whether the page renders a component held in state. + tmp_path: Directory for the compiled app. + monkeypatch: Fixture for changing the application directory. + mocker: Fixture for configuring the app and observing the app root. + """ + monkeypatch.chdir(tmp_path) + with RegistrationContext(): + + class ComponentState(rx.State): + """A state holding a component the frontend evaluates.""" + + component: rx.Component = rx.el.span("dynamic") + + mocker.patch( + "reflex_base.config._get_config", + return_value=rx.Config( + app_name="implicit_libraries", + plugins=[rx.plugins.RadixThemesPlugin()], + frontend_lazy_bundled_libraries=lazy, + ), + ) + bundle_library("d3-format@3.1.0") + app = rx.App() + app.add_page( + lambda: rx.el.div( + rx.text("static"), ComponentState.component if dynamic else None + ), + route="index", + ) + compile_app_root = mocker.spy(compiler, "compile_app_root") + compiler.compile_app(app, dry_run=True, use_rich=False) + + _, code = compile_app_root.spy_return + optional = ["d3-format", *(["@radix-ui/themes"] if dynamic else [])] + namespace_imports = [ + 'import * as React from "react";', + 'import * as emotion_react from "@emotion/react";', + 'import * as utils_context from "$/utils/context";', + 'import * as utils_context_registry from "$/utils/context-registry";', + 'import * as utils_state from "$/utils/state";', + ] + if not lazy: + namespace_imports += [ + 'import * as d3_format from "d3-format";', + *( + ['import * as radix_ui_themes from "@radix-ui/themes";'] + if dynamic + else [] + ), + ] + assert [ + line for line in code.splitlines() if line.startswith("import * as ") + ] == namespace_imports + assert [line.strip() for line in code.splitlines() if "() => import(" in line] == ( + [f'"{library}": () => import("{library}"),' for library in optional] + if lazy + else [] + ) + + def _mock_config_color_mode(mocker: MockerFixture, mode: LiteralColorMode) -> None: """Point the compiler's get_config at a fresh config with the given mode.