Using from JavaScript
Use Xote's compiled runtime from JavaScript projects without ReScript JSX.
Xote is ReScript-first, but the package also ships JavaScript modules you can import from a JavaScript app.
The main difference is syntax. ReScript projects use Xote's JSX (see the Quick start); JavaScript projects call the runtime constructors directly.
Install
1npm install xote
Use the client entry
For UI rendered in the browser, import from xote/client. It has the core rendering modules without the router, SSR, hydration or MDX code.
1import { Signal, Computed, Effect, View } from "xote/client";
Use the other entries only when a feature needs them:
xote/clientfor client-side viewsxote/routerfor routingxote/ssrfor server renderingxote/hydrationfor client hydrationxote/mdxfor MDX integration
Example: counter
Build views with View.element(tag, attrs, events, children). Attributes are View.attr(name, value) pairs; events are [eventName, handler] pairs.
1import { Signal, Computed, Effect, View } from "xote/client";23const count = Signal.make(0);4const doubled = Computed.make(() => Signal.get(count) * 2);56Effect.run(() => {7 console.log("Count:", Signal.get(count));8});910const increment = () => {11 Signal.update(count, n => n + 1);12};1314const app = View.element("main", [View.attr("class", "counter")], [], [15 View.element("h1", [], [], [View.text("Counter")]),16 View.element("p", [], [], [17 View.text("Count: "),18 View.signalText(() => String(Signal.get(count))),19 ]),20 View.element("p", [], [], [21 View.text("Doubled: "),22 View.signalText(() => String(Signal.get(doubled))),23 ]),24 View.element(25 "button",26 [View.attr("type", "button")],27 [["click", increment]],28 [View.text("Increment")],29 ),30]);3132View.mountById(app, "app");
The reactive reads happen inside Computed.make, Effect.run, and View.signalText. When count changes, the text nodes update in place.
Add Xote to an existing app
You can mount Xote into any existing DOM node:
1<div id="xote-widget"></div>2<script type="module" src="/src/widget.js"></script>
1import { Signal, View } from "xote/client";23const label = Signal.make("Save");45View.mountById(6 View.element("button", [], [["click", () => Signal.set(label, "Saved")]], [7 View.signalText(() => Signal.get(label)),8 ]),9 "xote-widget",10);
That makes JavaScript a good fit for small widgets, gradual adoption, and integration tests around the compiled runtime. For a new full app, prefer ReScript, so JSX and the type system work together. New to ReScript? Start with Learning ReScript.
Summary
Xote's compiled runtime can be used from plain JavaScript. ReScript functions compile to plain JS functions with positional arguments (labeled and optional arguments become positions; omitted optional arguments are undefined), ReScript option is undefined | value, and Xote nodes are plain objects built by View.* constructors. Without ReScript there is no PPX: reactivity in JS comes only from functions you pass to Computed.make, Effect.run, View.signalText, View.computedAttr, attribute thunks, and signals passed where a signal is expected. The package ships no TypeScript declarations.
Availability
| Entry (import specifier) | File | Exports |
|---|---|---|
xote | dist/xote.mjs (ESM), dist/xote.cjs (CJS), dist/xote.umd.js (UMD global xote) | Signal, Computed, Effect, View, Html, XoteJSX, MaybeSignal, Prop (deprecated), Context, Resource |
xote/client | dist/client.mjs / .cjs | same as xote |
xote/router | dist/router.mjs / .cjs | Router, Route, and init, initSSR, location, push, replace, route, routes, link, Link |
xote/ssr | dist/ssr.mjs / .cjs | SSR, SSRContext, SSRState, and renderToString, renderToStringWithRoot, renderDocument, generateHydrationScript |
xote/hydration | dist/hydration.mjs / .cjs | Hydration, hydrate, hydrateById |
xote/mdx | dist/mdx.mjs / .cjs | Mdx, render, components, component, childrenToNodes, childrenToText |
xote/signal, xote/computed, xote/effect, xote/view, xote/html, xote/jsx, xote/maybe-signal, xote/route, xote/ssr-context, xote/ssr-state | compiled ReScript sources (src/*.res.mjs, ESM only) | one module each |
xote/context, xote/resource | compiled sources, ESM only | 7.2.0 (new) |
xote/jsx-runtime, xote/jsx-dev-runtime | src/jsx-runtime.mjs | jsx, jsxs, Fragment (jsxDEV in the dev runtime): React-style automatic JSX runtime used by MDX |
Context and Resource inside xote/xote/client were added in 7.2.0. The PPX (@xote.component) is ReScript-only and unavailable in JS.
Rules
- Call ReScript functions with arguments in declaration order, labeled ones included. Optional trailing arguments may be omitted; a skipped middle optional MUST be passed as
undefined. Example:Signal.make(value, name, equals);View.element(tag, attrs, events, children, ref). option<'a>crosses the boundary asundefined(None) or the value (Some). An effect's function returnsundefinedor a cleanup function.- A ReScript variant crosses as an object with
TAG(and_0, …) or a string for constant constructors. Do not construct variants by hand; use the module's constructors (MaybeSignal.reactive(signal),MaybeSignal.$static(value)). - Identifiers that clash with JS reserved words are exported with a
$prefix:MaybeSignal.staticisMaybeSignal.$staticin JS. - Reactive text MUST be
View.signalText(() => string)(or aSignal.t<string>passed to APIs that take one). Children ofView.elementMUST be nodes (View.text,View.signalText,View.element, …); a function or signal is not a node. In JSX children, functions and signals are stringified, not reactive. - In
View.element, attributes are[name, attrValue]pairs built withView.attr(name, string)(static),View.signalAttr(name, signal), orView.computedAttr(name, () => string)(reactive). Events are[eventName, handler]pairs with DOM event names ("click","input"). - Lists:
View.each(signal, render)re-renders all items on change;View.eachWithKey(signal, keyFn, render)keeps items by string key. Use the keyed form for lists that reorder or contain inputs. - With the JSX runtime (
jsxImportSource: "xote"), attribute values that are functions become reactive attributes and signals passed as attribute values are reactive; children that are functions or signals are stringified (rendered as source text /[object Object]). UseView.signalTextfor reactive text in JSX children. - In the JSX runtime,
classNameandhtmlForare accepted and renamed toclass/for;onXxxfunction props become event listeners;styleaccepts a string or an object (camelCase keys are kebab-cased);attrstakes[name, value]pairs;reftakes aView.Ref.tor a callback (7.2.0). - A function component in the JSX runtime is called once (it becomes a lazy component node), like a ReScript component.
- No
.d.tsfiles are published; in TypeScript, declare the modules you use (declare module "xote/client") or allow JS. All values are effectivelyany.
API
| Name | JS call shape | Behaviour |
|---|---|---|
Signal.make | Signal.make(value, name?, equals?) | creates a signal |
Signal.get / Signal.peek | Signal.get(s) | tracked / untracked read |
Signal.set / Signal.update | Signal.set(s, v), Signal.update(s, f) | write; notifies dependents synchronously |
Signal.batch | Signal.batch(() => …) | one notification for several writes |
Computed.make | Computed.make(() => value, name?, equals?) | derived signal |
Effect.run | Effect.run(() => cleanup?, name?) | runs now and on change |
View.element | View.element(tag, attrs?, events?, children?, ref?) | element node |
View.text / View.signalText | View.text(string), View.signalText(() => string) | static / reactive text |
View.attr / View.signalAttr / View.computedAttr | (name, string), (name, signal), (name, () => string) | attribute entries |
View.fragment | View.fragment([nodes]) | grouping without an element |
View.each / View.eachWithKey | (signal, render), (signal, keyFn, render) | lists |
View.mountById / View.mount | (node, id), (node, element) | render into the DOM |
Html.div, Html.span, Html.button, … | see /docs/api/view | shorthand element constructors |
Patterns
Counter with View.element, use for widgets without a build step for JSX:
1import { Signal, Computed, View } from "xote/client";23const count = Signal.make(0);4const doubled = Computed.make(() => Signal.get(count) * 2);56const app = View.element("main", [View.attr("class", "counter")], [], [7 View.element("p", [], [], [8 View.text("Count: "),9 View.signalText(() => String(Signal.get(count))),10 ]),11 View.element("p", [View.computedAttr("class", () => (Signal.get(count) > 5 ? "high" : "low"))], [], [12 View.signalText(() => `Doubled: ${Signal.get(doubled)}`),13 ]),14 View.element(15 "button",16 [View.attr("type", "button")],17 [["click", () => Signal.update(count, n => n + 1)]],18 [View.text("Increment")],19 ),20]);2122View.mountById(app, "app");
Effect with cleanup, use for timers/listeners:
1import { Signal, Effect } from "xote/client";23const delay = Signal.make(1000);4Effect.run(() => {5 const id = setInterval(() => console.log("tick"), Signal.get(delay));6 return () => clearInterval(id);7});
Keyed list, use for lists that change:
1import { Signal, View } from "xote/client";23const items = Signal.make([{ id: "a", text: "A" }, { id: "b", text: "B" }]);4const list = View.element("ul", [], [], [5 View.eachWithKey(items, item => item.id, item => View.element("li", [], [], [View.text(item.text)])),6]);
JSX in JavaScript (automatic runtime), use when a JSX toolchain is already present. Configure the compiler with jsx: "automatic" and jsxImportSource: "xote" (esbuild/Vite: esbuild: { jsx: "automatic", jsxImportSource: "xote" }; Babel: @babel/preset-react with runtime: "automatic", importSource: "xote"):
1import { Signal, View } from "xote/client";23const count = Signal.make(0);45export const Counter = () => (6 <button class={() => (Signal.get(count) > 0 ? "on" : "off")} onClick={() => Signal.update(count, n => n + 1)}>7 Count: {View.signalText(() => String(Signal.get(count)))}8 </button>9);
Static vs reactive MaybeSignal from JS:
1import { MaybeSignal, Signal } from "xote/client";2const fixed = MaybeSignal.$$static(10);3const live = MaybeSignal.reactive(Signal.make(10));
Anti-patterns
Function as a child:
1View.element("p", [], [], [() => String(Signal.get(count))]);
Symptom: a function is not a node; in Xote 7.2.0-beta.2, mounting this element did not return (the page hangs). Fix: View.signalText(() => String(Signal.get(count))).
JSX child as a thunk or signal:
1<p>{() => Signal.get(count)}</p>
Symptom: the text is the function's source code; a signal child renders [object Object]. Fix: <p>{View.signalText(() => String(Signal.get(count)))}</p>.
Labeled arguments passed as an object:
1View.element("div", { attrs: [], children: [] });
Symptom: TypeError: … forEach is not a function when mounted; arguments are positional. Fix: View.element("div", [], [], []).
MaybeSignal.static(1): undefined at runtime. Fix: MaybeSignal.$static(1).
Non-string text: View.text and View.signalText are typed for strings (string, unit => string). A number happens to render (View.text(42) shows 42) but is outside the contract. Fix: String(…).
Edge cases
View.mountByIdlogsContainer element not found: <id>and does nothing if the element is missing.- Each
Signal.setnotifies dependents synchronously; two writes run a dependent effect twice unless wrapped inSignal.batch. - Signal equality is
===: setting a new object with the same contents notifies; passequalsas the third argument ofSignal.maketo change it. xote/signaland the other source subpaths are ESM-only; CommonJS consumers usexote,xote/client,xote/router,xote/ssr,xote/hydrationorxote/mdx.- The
xoteUMD bundle exposes the globalxote(e.g.xote.Signal).
SSR and hydration
From Node: import { renderToString } from "xote/ssr" and call renderToString(() => node); SSRContext.isServer / isClient are booleans. In the browser: import { hydrateById } from "xote/hydration" and call hydrateById(() => node, "root") with the same node tree the server rendered. See /docs/advanced/ssr.
Verify
node -e "import('xote/client').then(m => console.log(Object.keys(m)))"lists the modules.- Render to a string without a DOM:
import { renderToString } from "xote/ssr"; renderToString(() => View.element("p", [], [], [View.text("ok")]))returns<p>ok</p>. - In jsdom: mount,
Signal.set, then assert the text node changed and the element is the same object.
Related
/docs/learning-rescript— why ReScript is the primary language and how interop works./docs/api/view— everyViewconstructor./docs/advanced/mdx-support— the JSX runtime in MDX.