Skip to content

Using from JavaScript

Use Xote's compiled runtime from JavaScript projects without ReScript JSX.

docs/javascript.md
Raw Markdown

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/client for client-side views
  • xote/router for routing
  • xote/ssr for server rendering
  • xote/hydration for client hydration
  • xote/mdx for 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";
2
3const count = Signal.make(0);
4const doubled = Computed.make(() => Signal.get(count) * 2);
5
6Effect.run(() => {
7 console.log("Count:", Signal.get(count));
8});
9
10const increment = () => {
11 Signal.update(count, n => n + 1);
12};
13
14const 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]);
31
32View.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";
2
3const label = Signal.make("Save");
4
5View.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)FileExports
xotedist/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/clientdist/client.mjs / .cjssame as xote
xote/routerdist/router.mjs / .cjsRouter, Route, and init, initSSR, location, push, replace, route, routes, link, Link
xote/ssrdist/ssr.mjs / .cjsSSR, SSRContext, SSRState, and renderToString, renderToStringWithRoot, renderDocument, generateHydrationScript
xote/hydrationdist/hydration.mjs / .cjsHydration, hydrate, hydrateById
xote/mdxdist/mdx.mjs / .cjsMdx, 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-statecompiled ReScript sources (src/*.res.mjs, ESM only)one module each
xote/context, xote/resourcecompiled sources, ESM only7.2.0 (new)
xote/jsx-runtime, xote/jsx-dev-runtimesrc/jsx-runtime.mjsjsx, 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

  1. 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).
  2. option<'a> crosses the boundary as undefined (None) or the value (Some). An effect's function returns undefined or a cleanup function.
  3. 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)).
  4. Identifiers that clash with JS reserved words are exported with a $ prefix: MaybeSignal.static is MaybeSignal.$static in JS.
  5. Reactive text MUST be View.signalText(() => string) (or a Signal.t<string> passed to APIs that take one). Children of View.element MUST 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.
  6. In View.element, attributes are [name, attrValue] pairs built with View.attr(name, string) (static), View.signalAttr(name, signal), or View.computedAttr(name, () => string) (reactive). Events are [eventName, handler] pairs with DOM event names ("click", "input").
  7. 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.
  8. 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]). Use View.signalText for reactive text in JSX children.
  9. In the JSX runtime, className and htmlFor are accepted and renamed to class/for; onXxx function props become event listeners; style accepts a string or an object (camelCase keys are kebab-cased); attrs takes [name, value] pairs; ref takes a View.Ref.t or a callback (7.2.0).
  10. A function component in the JSX runtime is called once (it becomes a lazy component node), like a ReScript component.
  11. No .d.ts files are published; in TypeScript, declare the modules you use (declare module "xote/client") or allow JS. All values are effectively any.

API

NameJS call shapeBehaviour
Signal.makeSignal.make(value, name?, equals?)creates a signal
Signal.get / Signal.peekSignal.get(s)tracked / untracked read
Signal.set / Signal.updateSignal.set(s, v), Signal.update(s, f)write; notifies dependents synchronously
Signal.batchSignal.batch(() => …)one notification for several writes
Computed.makeComputed.make(() => value, name?, equals?)derived signal
Effect.runEffect.run(() => cleanup?, name?)runs now and on change
View.elementView.element(tag, attrs?, events?, children?, ref?)element node
View.text / View.signalTextView.text(string), View.signalText(() => string)static / reactive text
View.attr / View.signalAttr / View.computedAttr(name, string), (name, signal), (name, () => string)attribute entries
View.fragmentView.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/viewshorthand element constructors

Patterns

Counter with View.element, use for widgets without a build step for JSX:

1import { Signal, Computed, View } from "xote/client";
2
3const count = Signal.make(0);
4const doubled = Computed.make(() => Signal.get(count) * 2);
5
6const 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]);
21
22View.mountById(app, "app");

Effect with cleanup, use for timers/listeners:

1import { Signal, Effect } from "xote/client";
2
3const 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";
2
3const 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";
2
3const count = Signal.make(0);
4
5export 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.mountById logs Container element not found: <id> and does nothing if the element is missing.
  • Each Signal.set notifies dependents synchronously; two writes run a dependent effect twice unless wrapped in Signal.batch.
  • Signal equality is ===: setting a new object with the same contents notifies; pass equals as the third argument of Signal.make to change it.
  • xote/signal and the other source subpaths are ESM-only; CommonJS consumers use xote, xote/client, xote/router, xote/ssr, xote/hydration or xote/mdx.
  • The xote UMD bundle exposes the global xote (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.
  • /docs/learning-rescript — why ReScript is the primary language and how interop works.
  • /docs/api/view — every View constructor.
  • /docs/advanced/mdx-support — the JSX runtime in MDX.