Import JavaScript modules from Python and call their exports by name
Type of change
- New feature (non-breaking change which adds functionality)
- This change requires a documentation update
Description
Second of the ENG-9127 stack, on top of reflex-dev/reflex#7949.
Problem. More than a line of JavaScript ends up as strings passed to rx.call_script. Those strings get no editor support or lint, the browser evals them, and they break under a Content Security Policy without unsafe-eval.
Change. Write the JavaScript in a .js, .ts, .jsx or .tsx file in your app package, and import its exported functions from Python:
// 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 report(handler, value) {
reflex.addEvents([reflex.event(handler, { value })]);
}
from my_app.scripts.party import celebrate, report
rx.button("🎉", on_click=celebrate(PartyState.count, "results"))
rx.button("Report", on_click=report(PartyState.done, "clicked"))
Each named export becomes a Python function that returns an event. Use it in an event trigger, or return or yield it from a handler. Passed to a trigger without being called, it receives the trigger's arguments. The browser receives the module, the function name and the arguments as JSON, and evaluates nothing.
Rules.
- Only modules inside the app's own package can be imported.
.jsfiles in other installed packages are never claimed. - Local files a module imports (
./helpers.js, CSS with its@import/url()references, images) are bundled with it, resolved by Vite itself. They must be inside the app package's directory. - npm packages the module imports are installed with the app. Imports that are not packages are skipped:
virtual:,#…,@/…and type-only imports. A Node built-in with no browser package (fs,node:*) stops the compile with an error. - The function's return value is not sent back. Report results with
reflex.addEvents. from module import *is not supported: Python does not read the file, so it cannot list its exports.- Import a module at module level. A module first imported inside an event handler is not in the compiled frontend, so that import raises an error that says to move it.
- A module function is an event handler: an uncalled one works as a trigger (it receives the trigger's arguments), as
callback=, insiderx.cond, returned from a handler, and with event actions such as.debounce()(each function keeps its own debounce and throttle timer). An event handler argument arrives as its full name, and a bound event as{name, payload}, also inside lists and dicts, from a trigger and from a handler alike. - In dev, Vite serves an edit to any file a module reaches, data files included, without a backend restart. An edit to a script or stylesheet also reloads the backend, under Granian and Uvicorn, so the export checks and stubs follow.
Errors. Each one states the problem, its cause and the fix, and is pinned by an exact test. All are raised when the app compiles:
- A name used from Python that the module does not export (
nope): names the file, lists its functions, and shows theexport function nope() { ... }to add. export const notAFunction = 5used from Python: it is a value, not a function, which Python cannot call.- A syntax error in a module or a file it imports:
file:line:columnand the parser's message. - A local import outside the app package, or a Node built-in.
- In the browser, a missing function names the likely cause: a frontend older than the backend.
Design.
- Python does not read JavaScript. Importing a module registers its path. Its
__getattr__returns a function for any name and records the name. The backend needs no parser and no Node.js:--backend-onlydeployments are unaffected. - The compile reads modules with the bundler's parser.
script-modules.jsruns in.webwith the oxc parser that ships with rolldown, which Vite 8 installs in every app. It reports each module's function and value exports, its local files and its npm imports, so JS, TS, JSX and TSX are parsed exactly. This replaces an earlier hand-written tokenizer (~890 lines). The compile then checks every name Python used. The node call takes ~40 ms, and only for apps that import a module. The first compile of such an app installs the frontend packages before reading the modules, because the parser comes with them. - Lazy finder. The meta-path finder is registered lazily, so
import reflexdoesn't load the event system. It sits beforePathFinderand runs its search first: a Python module always wins, and a directory without__init__.pyno longer hides a script of its name. It claims a module only if a matching script exists under the app package, reads the config only then, and declines whilerxconfig.pyitself loads. - Linked, not copied.
.web/utils/script_modules/<package>is a link to the app package (a directory junction on Windows), and Vite resolves withpreserveSymlinks, so the module's imports,.js→.tsxmapping, CSS@imports and assets are resolved by Vite, a deleted file is gone at once, and nothing is copied or cleaned up. A build must run where the app package is: one that copies only.webelsewhere breaks the link. - One lazy chunk per module.
utils/scripts.jsmaps module names to() => import(...)with JSON-escaped strings, so each module is its own lazy chunk in the production build. Loading starts at page load and is cached, so a module function runs before anything awaited after it. - Event queue. The queue alone orders module calls: a call stays at the head of the queue while its module loads, so no later event starts first, even from concurrent drains (
state_connection.test.jspins those). The function is then called without awaiting the promise it returns, so a slow or never-settling function holds up no later event. The misleading comment above its empty-queue check now says what the check does. - Includes reflex-dev/reflex#7961. The
*args/**kwargsfix for callables passed to triggers comes from there, merged in until it lands.
Tests
- Unit (
test_finder.py,test_modules.py,test_compiler_utils.py,test_compiler.py): the import scope, name recording, the compile-time checks and their exact messages, the folder limit, generated module names, npm detection, the script runner (real Node), and install ordering. - vitest:
script-modules.json fixtures (TS, JSX/TSX, CSS, assets, dynamic imports,export *, type-only exports),_call_js, and the ordering of a module function before the next event. - Playwright
test_call_script.py: module functions from a trigger and from a handler, an async function, an npm package, CSS, an uncalledon_change, and the ordering. - Coverage: 100% of the added Python lines and branches and JS statements. ruff, pyright and
npm run checkare clean.