feat: hoist large literals into shared modules with LiteralVar.hoist()

BE
2d ago
+732-46

A LiteralVar is written out in full at every reference, so a large constant used in several places repeats in the compiled JS. In this repro a 20-entry list (~22 KB) read by three conditions compiles to a 66 KB route chunk:

BIG = [f"searchable text of post {i} " * 40 for i in range(20)]


def cards() -> rx.Component:
    query = rx.client_state("")
    texts = rx.Var.create(BIG)
    return rx.el.div(
        rx.el.input(on_change=query.set),
        *[rx.cond(texts[i].contains(query.value), rx.el.p(f"card {i}")) for i in range(3)],
    )

LiteralVar.hoist() moves the value into .web/utils/hoisted/hoisted_<content hash>.js and returns a var of the same type that renders as that name, with the module's import in its VarData. The import follows the var into whichever page or memo module renders it, so the bundler emits the value once and shares it between pages. With texts = rx.Var.create(BIG).hoist() the route chunk holds the list once: 65,741 → 23,231 bytes (gzip 1,224 → 1,007). In a real app, a blog search index read from 33 places shipped 33 copies (604 KB).

  • Equal literals hoist to the same module. Names are content hashes, so they are the same in every process.
  • Only constant literals can be hoisted (checked with get_leaf_vars); a hoisted literal may hold other hoisted ones.
  • At the end of compile_app, a module is written for each hoisted literal the compiled modules import (and the ones it holds), and pruned through a manifest of its own that shares the memo manifest's helpers.
  • Code the browser evaluates outside any module cannot import it: call_script/call_function sent from the backend (through Var._decode), script callbacks, and dynamic components. Such an expression is wrapped in an arrow function binding each hoisted literal it reads to its value, found through its var data (format_queue_events now keeps the var data of the events it formats); a dynamic component declares them as consts, with their imports.

It is opt-in rather than applied to every literal in _cached_var_name: a module per small literal costs more than it saves, and the backend-rendered code above would need the fallback on every path.