Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/+window-libraries-dynamic-only.performance.md
Original file line number Diff line number Diff line change
@@ -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("<library>")`, which always exposes it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The note incorrectly says compiler-registered libraries are exposed only when a page evaluates a state-held component. With the default eager loading, the app root exposes them whenever the compiled app includes the dynamic-component evaluator, even if no dynamic component is ever rendered; distinguish eager and lazy behavior in this sentence.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At news/+window-libraries-dynamic-only.performance.md, line 1:

<comment>The note incorrectly says compiler-registered libraries are exposed only when a page evaluates a state-held component. With the default eager loading, the app root exposes them whenever the compiled app includes the dynamic-component evaluator, even if no dynamic component is ever rendered; distinguish eager and lazy behavior in this sentence.</comment>

<file context>
@@ -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("<library>")`, which always exposes it.
</file context>
Suggested change
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("<library>")`, which always exposes it.
Apps that render no dynamic component no longer import implicit 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 exposed for apps whose compiled code includes a dynamic-component evaluator, and lazy loading defers optional libraries until that evaluator runs. A script that reads one of them from `window.__reflex` directly must register it with `bundle_library("<library>")`, which always exposes it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: bundle_library does not always make a library available on window.__reflex at startup. With frontend_lazy_bundled_libraries=True, explicitly registered non-default libraries are added only after window.__reflex_load() runs, so qualify this compatibility guidance and tell direct readers to await the loader.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At news/+window-libraries-dynamic-only.performance.md, line 1:

<comment>`bundle_library` does not always make a library available on `window.__reflex` at startup. With `frontend_lazy_bundled_libraries=True`, explicitly registered non-default libraries are added only after `window.__reflex_load()` runs, so qualify this compatibility guidance and tell direct readers to await the loader.</comment>

<file context>
@@ -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("<library>")`, which always exposes it.
</file context>
Suggested change
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("<library>")`, which always exposes it.
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("<library>")`; when `frontend_lazy_bundled_libraries` is enabled, it must also await `window.__reflex_load()` before reading it.

Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions packages/reflex-base/src/reflex_base/components/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
47 changes: 40 additions & 7 deletions reflex/compiler/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -166,19 +174,25 @@ 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.

Args:
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())
Expand Down Expand Up @@ -720,14 +734,20 @@ 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.

Args:
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.
Expand All @@ -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


Expand Down Expand Up @@ -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()
Expand Down
17 changes: 17 additions & 0 deletions tests/integration/tests_playwright/test_radix_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
94 changes: 94 additions & 0 deletions tests/units/compiler/test_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading