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. 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.
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 claims a module only if a matching script exists under the app package, and reads the config only then. - 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.
processEventintentionally lets several drains run at once (state_connection.test.jspins that). So events wait only behind a pending module call rather than behind a global in-flight guard. 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.