Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
9082d98
Import JavaScript modules from Python and call their exports by name
FarhanAliRaza Nov 20, 2026
15dc4dc
Merge branch 'farhan/focused-darwin-dx76ek-env' into farhan/focused-d…
FarhanAliRaza Nov 20, 2026
c0ebd9c
Read JS modules with a tokenizer, copy their import graph, keep impor…
FarhanAliRaza Nov 20, 2026
e735021
Merge branch 'farhan/focused-darwin-dx76ek-env' into farhan/focused-d…
FarhanAliRaza Nov 20, 2026
9108fef
Copy JS module assets byte for byte and follow stylesheet references
FarhanAliRaza Nov 20, 2026
9f708ac
Register the JS module finder without loading a module for it
FarhanAliRaza Nov 20, 2026
ec37f31
Pass every trigger argument to *args callables; resolve query imports
FarhanAliRaza Nov 20, 2026
c65c654
Add docstrings to the tokenizer helpers
FarhanAliRaza Nov 20, 2026
1af25b3
Merge branch 'farhan/focused-darwin-dx76ek-env' into farhan/focused-d…
FarhanAliRaza Nov 21, 2026
780ebe3
Pass a trigger's arguments only to positional parameters
FarhanAliRaza Nov 21, 2026
b1ee1e4
Rework JavaScript module imports after review
FarhanAliRaza Nov 21, 2026
248a571
Test that a script sees what a module function did first
FarhanAliRaza Nov 21, 2026
f9e1852
Document JavaScript modules usage-first, with every error
FarhanAliRaza Nov 21, 2026
19483fb
Test errors of event code; drop unreachable import-clause checks
FarhanAliRaza Nov 21, 2026
a15fd40
Say why the loader imports the event system lazily
FarhanAliRaza Nov 21, 2026
660a450
Format the _call_js tests
FarhanAliRaza Nov 21, 2026
d854e12
Hold events back while a module call waits for its module
FarhanAliRaza Nov 21, 2026
31c16d9
Find dynamic imports inside template and JSX expressions
FarhanAliRaza Nov 21, 2026
1d464d9
Hold an event back behind every module call before it
FarhanAliRaza Nov 21, 2026
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
111 changes: 111 additions & 0 deletions docs/api-reference/browser_javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,117 @@ event handlers that take no arguments, such as `SearchState.clear`.
the members of `reflex` instead of Reflex internals, and import your own
modules from a JavaScript module.

## JavaScript Modules

Write JavaScript in a `.js` or `.ts` file in your app's package and import its
exported functions in Python, like a Python module. Each function returns an
event: use it in an event trigger, or return or yield it from an event handler.

```javascript
// my_app/scripts/party.js
import confetti from "canvas-confetti";
import { reflex } from "$/utils/reflex";

export function celebrate(count, elementId) {
confetti({ particleCount: count });
document.getElementById(elementId).scrollIntoView();
}

export function measure(id, handler) {
const { width } = document.getElementById(id).getBoundingClientRect();
reflex.addEvents([reflex.event(handler, { width })]);
}
```

```python
# my_app/my_app.py
import reflex as rx

from my_app.scripts.party import celebrate, measure


class PartyState(rx.State):
count: int = 200
width: float = 0

@rx.event
def finish(self):
return celebrate(self.count, "results")

@rx.event
def set_width(self, width: float):
self.width = width


def index():
return rx.vstack(
rx.button("Celebrate", on_click=celebrate(PartyState.count, "results")),
rx.button("Finish", on_click=PartyState.finish),
rx.button("Measure", on_click=measure("results", PartyState.set_width)),
rx.text(f"Width: {PartyState.width}", id="results"),
)


app = rx.App()
app.add_page(index)
```

Nothing is evaluated: the module is bundled with the app, and calling one of its
functions sends only the module's name, the function's name and the arguments.
Apps whose Content Security Policy forbids `unsafe-eval` can use them.

### Rules

- Only modules in your app's package import this way: the package that
`app_name` in `rxconfig.py` names. A `.js` file in another package, such as
a library you installed, is never imported.
- A Python module of the same name wins over a JavaScript one.
- Every named export that may be a function becomes a function. A `const`
initialized with a literal, as in `export const limit = 5`, is a value, and
Python cannot call it. A default export, a class and TypeScript types are
left out.
- Arguments are sent as JSON. A var is sent as its value in the browser. An
event handler arrives as its full name, which the function dispatches with
`reflex.addEvents([reflex.event(name, payload)])`, as `measure` does above.
- The function's return value is not sent back. To get a value back, pass an
event handler and dispatch it with the value, as `measure` does.
- The npm packages the module imports, such as `canvas-confetti`, are installed
with the app. Pin a version with `frontend_packages` in `rxconfig.py`. Path
aliases (`@/...`), subpath imports (`#...`) and specifiers with a scheme
(`virtual:...`, `https://...`) are left to the bundler and not installed.
- Local files the module imports with relative paths, such as `./helpers.js`,
`./party.css` or `./logo.png`, are bundled with it, and so are the files they
import, including a stylesheet's `@import` and `url(...)` references. They
must be inside your app's package directory, which is all of your project
that is copied into the compiled app.
- In a `.jsx` or `.tsx` file, JSX is read as JSX. In a `.js` or `.ts` file,
`<` is never JSX, so a quote in what would be JSX text hides the code after
it on that line.
- Reflex writes a type stub (`party.pyi`) next to the module when it compiles
the app, so type checkers resolve the import.

### Errors

- `Cannot import nope from my_app.scripts.party: .../party.js exports no
function named nope (its functions: celebrate, measure).` Export the function
from the file, as in `export function nope() { ... }`, or fix the name you
import.
- `Cannot import limit from my_app.scripts.party: .../party.js exports limit as
a value, not a function, and Python can only call functions.` Export a
function that uses the value instead.
- `The JavaScript module my_app.scripts.party imports .../shared.js, which is
outside .../my_app, the directory of the app's package, and only that
directory is copied into the compiled app.` Move the file into your app's
package, or publish it as an npm package and import it by name.
- `The JavaScript file .../party.js imports 'fs', a Node.js built-in module,
which does not exist in the browser.` Remove the import, and do the work that
needs it in a backend event handler instead.
- In the browser, `Cannot call my_app.scripts.party.nope: the frontend has no
function nope in the JavaScript module my_app.scripts.party.` The module does
not export a function of that name, or the frontend was built before the
backend imported it. Export the function, or restart `reflex run` to rebuild
the frontend.

## Using React Hooks

To use React Hooks directly in a Reflex app, you must subclass `rx.Component`,
Expand Down
7 changes: 7 additions & 0 deletions news/+js-modules.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Import functions from a `.js` or `.ts` file in your app's package like a Python module, and call them from event triggers and event handlers. The module is bundled with the app and its npm imports are installed; see [JavaScript Modules](https://reflex.dev/docs/api-reference/browser-javascript/#javascript-modules).

```python
from my_app.scripts.party import celebrate

rx.button("🎉", on_click=celebrate(200, "results"))
```
1 change: 1 addition & 0 deletions packages/reflex-base/news/+js-modules.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The `_call_js` event calls a function of one of the app's JavaScript modules by name, with JSON arguments, so the frontend evaluates no code. `utils/scripts.js` maps each module's Python name to a function that loads it, and the page loads them as it starts.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A callable passed to an event trigger gets the trigger's arguments only through its positional parameters: `lambda *args: ...` gets all of them, even none, and `lambda key, **kwargs: ...` or a keyword-only parameter no longer raises `TypeError`.
52 changes: 52 additions & 0 deletions packages/reflex-base/src/reflex_base/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,53 @@
"""Reflex core types."""

from __future__ import annotations

import sys

# Not imported from typing, which `import reflex` does not load otherwise.
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Sequence
from importlib.machinery import ModuleSpec
from types import ModuleType


class _ScriptFinder:
"""Let app code import the JavaScript modules beside it.

Registered here, by the package every Reflex import loads first, so that
no module is loaded for it: the real finder, ``reflex_base.js.finder``,
loads on the first import of a submodule no other finder found.
"""

@staticmethod
def find_spec(
fullname: str,
path: Sequence[str] | None,
target: ModuleType | None = None,
) -> ModuleSpec | None:
"""Find the JavaScript file for a submodule.

Args:
fullname: The dotted module name.
path: The search path of the parent package; None for a top-level
module, which is never a JavaScript module.
target: Unused.

Returns:
The spec of the JavaScript module, or None.
"""
if path is None:
return None
from reflex_base.js.finder import find_spec

return find_spec(fullname, path)


# By name, not identity: importing this module afresh, as a reload or a
# benchmark that clears sys.modules does, must not register a second one.
if not any(
isinstance(finder, type) and finder.__qualname__ == "_ScriptFinder"
for finder in sys.meta_path
):
sys.meta_path.append(_ScriptFinder)
4 changes: 4 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ class Dirs(SimpleNamespace):
CLIENT_STATE_PATH = UTILS + "/client_state"
# The module defining `reflex`, the API JavaScript reaches Reflex through.
REFLEX_API_PATH = UTILS + "/reflex"
# The index of the JavaScript modules an app imports from Python.
SCRIPTS_PATH = UTILS + "/scripts"
# The directory those modules are copied to.
SCRIPT_MODULES_PATH = UTILS + "/script_modules"
# The name of the output directory.
BUILD_DIR = "build"
# The name of the static files directory.
Expand Down
56 changes: 48 additions & 8 deletions packages/reflex-base/src/reflex_base/event/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2624,6 +2624,50 @@ def args_specs_from_fields(
}


# The parameters a trigger's arguments are passed to, in order. `*args` takes
# any number of them, none included; keyword-only parameters and `**kwargs`
# take none.
_POSITIONAL_PARAMETER_KINDS = (
inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
)


def _positional_parameters(
parameters: Mapping[str, inspect.Parameter],
) -> list[inspect.Parameter]:
"""Get the parameters a trigger's arguments are passed to.

Args:
parameters: The parameters of the function.

Returns:
Its positional parameters, in order.
"""
return [
parameter
for parameter in parameters.values()
if parameter.kind in _POSITIONAL_PARAMETER_KINDS
]


def _max_positional_args(parameters: Mapping[str, inspect.Parameter]) -> int | None:
"""Get how many of a trigger's arguments a function takes.

Args:
parameters: The parameters of the function.

Returns:
The number of its positional parameters, or None when it takes ``*args``.
"""
if any(
parameter.kind is inspect.Parameter.VAR_POSITIONAL
for parameter in parameters.values()
):
return None
return len(_positional_parameters(parameters))


def check_fn_match_arg_spec(
user_func: Callable,
user_func_parameters: Mapping[str, inspect.Parameter],
Expand All @@ -2646,15 +2690,13 @@ def check_fn_match_arg_spec(
Raises:
EventFnArgMismatchError: Raised if the number of mandatory arguments do not match
"""
user_args = list(user_func_parameters)
user_args = _positional_parameters(user_func_parameters)
# Drop the first argument if it's a bound method
if inspect.ismethod(user_func) and user_func.__self__ is not None:
user_args = user_args[1:]

user_default_args = [
p.default
for p in user_func_parameters.values()
if p.default is not inspect.Parameter.empty
p.default for p in user_args if p.default is not inspect.Parameter.empty
]
number_of_user_args = len(user_args) - number_of_bound_args
number_of_user_default_args = len(user_default_args) if user_default_args else 0
Expand Down Expand Up @@ -2748,10 +2790,8 @@ def call_event_fn(
# Check that fn signature matches arg_spec
check_fn_match_arg_spec(fn, parameters, parsed_args, key=key)

number_of_fn_args = len(parameters)

# Call the function with the parsed args.
out = fn(*[*parsed_args][:number_of_fn_args])
# Call the function with as many of the parsed args as it takes.
out = fn(*parsed_args[: _max_positional_args(parameters)])

def _dispatch_mixed_event_var(event_like_var: Var) -> FunctionVar:
"""Wrap a mixed event-like Var into a callable frontend dispatcher.
Expand Down
16 changes: 16 additions & 0 deletions packages/reflex-base/src/reflex_base/js/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Build calls on ``reflex``, the API browser code reaches Reflex through."""

from reflex_base.utils import lazy_loader

# Not imported from typing, which `import reflex` does not load otherwise.
TYPE_CHECKING = False
if TYPE_CHECKING:
from .api import add_events, library, ref

__all__ = ["add_events", "library", "ref"]

# Lazy: the module finder `import reflex` registers lives in this package, and
# loading it must not load the event and var systems.
__getattr__, __dir__, __all__ = lazy_loader.attach(
__name__, submod_attrs={"api": ["add_events", "library", "ref"]}
)
98 changes: 98 additions & 0 deletions packages/reflex-base/src/reflex_base/js/finder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Import JavaScript modules from Python.

``from my_app.scripts.party import celebrate`` finds ``my_app/scripts/party.js``
(or ``.ts``) when no Python module of that name exists and ``my_app`` is the
app's package. Other packages' JavaScript files are never imported.

``import reflex`` registers a small finder that loads this module on the first
import of a submodule no other finder found, which can happen while ``reflex``
itself loads, so it stays cheap: ``os.path`` instead of ``pathlib``, a loader
that implements the import protocol without the ``importlib.abc`` base class,
and no ``typing``. The config loads once a JavaScript file is found, and the
event system with the first JavaScript module imported.
"""

from __future__ import annotations

import os.path
from importlib.machinery import ModuleSpec

# Not imported from typing, which `import reflex` does not load otherwise.
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Sequence
from importlib.abc import Loader as _LoaderBase
from types import ModuleType
else:
_LoaderBase = object

# The extensions of the files a JavaScript module may be written in.
SCRIPT_EXTENSIONS = (".js", ".ts")


class _ScriptLoader(_LoaderBase):
"""Execute a JavaScript module by exposing its exports as functions."""

def __init__(self, path: str):
"""Create the loader.

Args:
path: The JavaScript file.
"""
self.path = path

def create_module(self, spec: ModuleSpec) -> None:
"""Use the default module creation.

Args:
spec: The module spec.
"""

def exec_module(self, module: ModuleType) -> None:
"""Populate the module with one function per export.

Args:
module: The module to populate.
"""
# Imported here: loading the finder must not load the event system,
# which only a JavaScript module being imported needs.
from pathlib import Path

from reflex_base.js.modules import _load_module

_load_module(module, Path(self.path))


def _app_package() -> str:
"""Get the name of the app's top-level package.

Returns:
The package ``rxconfig.py`` names, or an empty string without one.
"""
# Imported here: the config loads only once a JavaScript file is found.
from reflex_base.config import get_config

return get_config().module.partition(".")[0]


def find_spec(fullname: str, path: Sequence[str]) -> ModuleSpec | None:
"""Find the JavaScript file for a submodule of the app's package.

Args:
fullname: The dotted module name.
path: The search path of the parent package.

Returns:
The spec of the JavaScript module, or None if there is no such file or
it is outside the app's package.
"""
name = fullname.rpartition(".")[2]
for entry in path:
for extension in SCRIPT_EXTENSIONS:
# Not pathlib: see the module docstring.
file = os.path.join(entry, name + extension) # noqa: PTH118
if os.path.isfile(file): # noqa: PTH113
if fullname.partition(".")[0] != _app_package():
return None
return ModuleSpec(fullname, _ScriptLoader(file), origin=file)
return None
Loading