Project structure
Set up rescript.json, the entry file and a folder layout, and decide where each piece of state should live.
A Xote app is a ReScript project that Vite serves. This guide shows the files you need, how to lay them out, and where each kind of state should live.
Configure ReScript
rescript.json tells the compiler to output ES modules next to your sources (which Vite can serve directly), to use Xote's JSX transform, and to enable the @xote.component annotation:
1{2 "name": "my-app",3 "sources": [{ "dir": "src", "subdirs": true }],4 "package-specs": [{ "module": "esmodule", "in-source": true }],5 "suffix": ".res.mjs",6 "dependencies": ["xote"],7 "jsx": { "version": 4, "module": "XoteJSX" },8 "ppx-flags": ["xote/ppx/ppx"],9 "compiler-flags": ["-open Xote"]10}
"ppx-flags"enables@xote.component. Leave it out and you need explicit() => …thunks for reactive values."-open Xote"lets you writeSignal,ViewandRouterinstead ofXote.Signal."subdirs": truecompiles every folder undersrc, so you can organise files freely.
If you use pnpm, allow Xote's install script (pnpm approve-builds) so the PPX binary is set up. The Quick start covers installation in full.
Add the page and the entry file
Vite starts from index.html at the project root. Give it an element to mount into, and load the compiled entry module:
1<!doctype html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>My app</title>7 <link rel="stylesheet" href="/src/styles.css" />8 </head>9 <body>10 <div id="app"></div>11 <script type="module" src="/src/Main.res.mjs"></script>12 </body>13</html>
The entry file only mounts the root component:
1// src/Main.res2View.mountById(<App />, "app")
Keep it that small. The entry is the one place that touches the page, and everything else stays testable on its own.
Run it
Run the ReScript compiler in watch mode next to Vite. A typical package.json:
1{2 "scripts": {3 "res:dev": "rescript watch",4 "dev": "vite",5 "build": "rescript && vite build"6 }7}
Start npm run res:dev and npm run dev in two terminals. ReScript rewrites the .res.mjs files and Vite reloads the page.
Lay out your files
There is no required layout. This one scales well from a single page to a larger app:
1src/2 Main.res # mounts <App />3 App.res # root component, routes4 styles.css5 components/ # reusable UI: Header.res, Disclosure.res, Tabs.res6 pages/ # one file per route: HomePage.res, SettingsPage.res7 state/ # app-wide signals and the functions that change them
Two ReScript rules shape this:
- One component per module.
@xote.componentdefines the module'smake, so a file likeHeader.resis the<Header />component. Small helpers can live as submodules (module Tab = { … }insideTabs.res, used as<Tabs.Tab />). - Module names are global. Folders do not namespace modules, so every file name must be unique across
src. PreferSettingsPage.resoverpages/Settings.resnext tostate/Settings.res.
Decide where state lives
Pick the narrowest home that works.
Inside a component when only that component cares. Each instance gets its own signal, created when the component renders:
1// src/components/Disclosure.res2@xote.component3let make = (~label: string, ~children: View.node) => {4 let isOpen = Signal.make(false)56 <section class="disclosure">7 <button onClick={_ => Signal.update(isOpen, v => !v)}> {label} </button>8 {Signal.get(isOpen) ? children : View.null()}9 </section>10}
In a module when many parts of the app share it: the signed-in user, a cart, settings. Put the signals and the functions that change them together:
1// src/state/Session.res2let user: Signal.t<option<string>> = Signal.make(None)34let signIn = name => Signal.set(user, Some(name))5let signOut = () => Signal.set(user, None)
Any component can read Signal.get(Session.user) and update when it changes. There is no provider to set up.
In context New in 7.2 when the value belongs to one part of the tree, and each copy of that part needs its own. Tabs are the classic case: each <Tabs> provides its own selection to the <Tabs.Tab> buttons inside it:
1// src/components/Tabs.res2let selected = Context.make(Signal.make(0))34module Tab = {5 @xote.component6 let make = (~index: int, ~label: string) => {7 let current = Context.use(selected)8 <button9 class={Signal.get(current) == index ? "tab active" : "tab"}10 onClick={_ => Signal.set(current, index)}>11 {label}12 </button>13 }14}1516@xote.component17let make = (~children: View.node) => {18 Context.provide(selected, Signal.make(0))19 <div class="tabs" role="tablist"> {children} </div>20}
Then the root component puts the pieces together:
1// src/App.res2@xote.component3let make = () =>4 <main>5 <Header title="My app" />6 <Tabs>7 <Tabs.Tab index={0} label="Overview" />8 <Tabs.Tab index={1} label="Settings" />9 </Tabs>10 <Disclosure label="Details">11 <p> {"Hidden until opened."} </p>12 </Disclosure>13 </main>
Add routing and server rendering later
Nothing here needs to change when you add pages: give App.res a router and move each page into pages/. If you later render on the server, the same components run there; you add a server entry and a client entry that hydrates. See Server rendering.
Common mistakes
- Two files with the same name in different folders. ReScript reports a duplicate module. Rename one.
- Two components in one module. Only one
makeper module; move the second into its own file or a submodule. - Pointing
index.htmlatMain.res. Vite serves the compiledMain.res.mjs, so ReScript must be running (or have run) first. - Module-level state that should be per instance. A signal at the top of
Disclosure.reswould be shared by every disclosure. Create it insidemakeinstead.
Summary
A Xote app is a ReScript 12 project that compiles each .res file to an ES module (.res.mjs) next to it, served and bundled by Vite. It needs one rescript.json (with Xote's JSX module and PPX), an index.html with a mount element, an entry module that mounts the root component, and components organised as one component per module. State lives in the narrowest scope that works: the component body, a module, or a Context. The one rule that matters most: module (file) names are global across all source folders, and each module may define only one @xote.component.
Availability
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
XoteJSX JSX module, View.mountById, View.mount | xote | 7.0.0 | — | No |
@xote.component and its prebuilt PPX binary (xote/ppx/ppx) | xote | 7.1.0 | — | — |
Context (make, use, provide, Provider) | xote, xote/context | 7.2.0 (new) | — | No |
| ReScript compiler | rescript 12 | — | — | — |
Rules
rescript.jsonMUST set"jsx": {"version": 4, "module": "XoteJSX"}and list"xote"in"dependencies". Listing"xote"alone is sufficient; its own dependency (rescript-signals) is resolved transitively."ppx-flags": ["xote/ppx/ppx"]enables@xote.component. Without it, use@jsx.componentwith explicit thunks and value components (see/docs/learn/rendering)."compiler-flags": ["-open Xote"]makesSignal,Computed,Effect,View,Router, … available unqualified. Without it, every file needsopen Xote(or qualified names)."package-specs": {"module": "esmodule", "in-source": true}with"suffix": ".res.mjs"writesFoo.res.mjsnext toFoo.res;index.htmland Vite reference the compiled.res.mjs, never the.res.- A module's name is its file name, and module names MUST be unique across every source directory (
"subdirs": truedoes not namespace them). TwoDup.resfiles fail the build: "Duplicate module name: Dup … Rename one of these files." - A module MAY contain only one component (
@xote.componentor@jsx.component); a second one is a compile error ("Only one component definition is allowed for each module"). Put further components in submodules (module Tab = { @xote.component let make = … }, used as<Tabs.Tab />) or separate files. - A file's top-level component is used as
<FileName />from other modules. A module cannot reference itself by name ("The module or file X can't be found"), so mounting MUST happen in a separate entry module (e.g.Main.res). - The entry module SHOULD only initialise global services (
Router.init,SSRState.sync) and mount; components stay importable and testable without side effects. - A signal created in a component body is per instance and owned by that component. A signal created at module level is a single app-wide value with no owner (never disposed). A value provided with
Context.provideis per subtree. - Module-level code runs once, when the module is first imported, in every environment that imports it (browser, server render, prerender, tests). It MUST NOT touch
window/documentunguarded if the module is used on a server.
Where state lives
| Who needs it | How many copies | Put it in |
|---|---|---|
| One component instance | one per instance | Signal.make in the component body |
| The whole app (session, cart, settings) | one | module-level signals in state/X.res, with the functions that change them |
| One subtree, e.g. a tab group or form | one per subtree instance | a Context whose value is a signal, provided by the subtree's root component (7.2.0) |
| Data from the server | per view | a Resource in the component that shows it (7.2.0) |
| Values derived from any of the above | — | a Computed next to its inputs |
API
| Name | Signature | Behaviour |
|---|---|---|
View.mountById | (View.node, string) => unit | Renders into the element with that id. |
View.mount | (View.node, Dom.element) => unit | Renders into an element. |
Context.make | 'a => Context.t<'a> | Creates a context with a default value. |
Context.provide | (Context.t<'a>, 'a) => unit | In a component body: provides a value to what that component renders. Raises elsewhere. |
Context.use | Context.t<'a> => 'a | In a component body: nearest provided value, else the default. |
Patterns
rescript.json — Use when: creating or repairing a project.
1{2 "name": "my-app",3 "sources": [{ "dir": "src", "subdirs": true }],4 "package-specs": [{ "module": "esmodule", "in-source": true }],5 "suffix": ".res.mjs",6 "dependencies": ["xote"],7 "jsx": { "version": 4, "module": "XoteJSX" },8 "ppx-flags": ["xote/ppx/ppx"],9 "compiler-flags": ["-open Xote"]10}
index.html and entry — Use when: wiring the app to the page.
1<!doctype html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>My app</title>7 <link rel="stylesheet" href="/src/styles.css" />8 </head>9 <body>10 <div id="app"></div>11 <script type="module" src="/src/Main.res.mjs"></script>12 </body>13</html>
1// src/Main.res2View.mountById(<App />, "app")
package.json scripts — Use when: running and building.
1{2 "scripts": {3 "res:dev": "rescript watch",4 "dev": "vite",5 "build": "rescript && vite build"6 }7}
Run res:dev and dev concurrently in development.
Canonical layout — Use when: starting an app with more than one screen.
1src/2 Main.res # entry: Router.init(), mount <App />3 App.res # root component, routes4 styles.css5 components/ # Header.res, Disclosure.res, Tabs.res6 pages/ # HomePage.res, SettingsPage.res (unique names)7 state/ # Session.res: app-wide signals + their setters
App-wide state module — Use when: many components share a value.
1// src/state/Session.res2let user: Signal.t<option<string>> = Signal.make(None)3let signedIn = Computed.make(() => Signal.get(user)->Option.isSome)4let signIn = name => Signal.set(user, Some(name))5let signOut = () => Signal.set(user, None)
Readers call Signal.get(Session.user) in their JSX; writers call Session.signIn.
Per-instance state — Use when: every copy of a component needs its own value.
1// src/components/Disclosure.res2@xote.component3let make = (~label: string, ~children: View.node) => {4 let isOpen = Signal.make(false)5 <section class="disclosure">6 <button onClick={_ => Signal.update(isOpen, v => !v)}> {label} </button>7 {Signal.get(isOpen) ? children : View.null()}8 </section>9}
Per-subtree state with Context (7.2.0) — Use when: a compound component (tabs, accordion, form) shares state with its descendants, one copy per instance.
1// src/components/Tabs.res2let selected = Context.make(Signal.make(0))34module Tab = {5 @xote.component6 let make = (~index: int, ~label: string) => {7 let current = Context.use(selected)8 <button9 class={Signal.get(current) == index ? "tab active" : "tab"}10 onClick={_ => Signal.set(current, index)}>11 {label}12 </button>13 }14}1516@xote.component17let make = (~children: View.node) => {18 Context.provide(selected, Signal.make(0))19 <div class="tabs" role="tablist"> {children} </div>20}
Anti-patterns
-
Same file name in two folders. Wrong:
pages/Settings.resandstate/Settings.res. Symptom: "Could not initialize build: Duplicate module name: Settings". Right:SettingsPage.resandSettingsState.res. -
Two components in one file. Symptom: "Only one component definition is allowed for each module". Right: a submodule (
module Item = { @xote.component let make = … }) or a separate file. -
Mounting inside the component's own file. Wrong:
View.mountById(<App />, "app")at the bottom ofApp.res. Symptom: "The module or file App can't be found". Right: mount fromMain.res. -
Module-level signal for per-instance state. Wrong:
let isOpen = Signal.make(false)at the top ofDisclosure.res. Symptom: opening one disclosure opens all of them. Right: create the signal insidemake. -
index.htmlpointing at a.resfile, or a stale build. Wrong:<script type="module" src="/src/Main.res">. Symptom: Vite serves ReScript source as JavaScript (syntax error) or old output. Right:/src/Main.res.mjs, withrescript watchrunning. -
Context.provideoutside a component body. Symptom: it raises at runtime (there is no render to scope it to). Right: call it in the providing component's body, or use<Context.Provider context value>.
Edge cases
- Name component files in PascalCase (
MyButton.res): the module name is the file name, and<MyButton />is how other modules use it. - Submodule components are referenced with a dot (
<Tabs.Tab />); the parent file's ownmakeis<Tabs />. Context.useoutside a render (event handler, timer, module level) returns the context's default value, not the nearest provided one; capture it in the component body."namespace": trueinrescript.jsonprefixes module names for published libraries; applications do not need it.- Adding routing or SSR later does not change this layout:
App.resgainsRouter.routes, and SSR addsEntryServer.res/EntryClient.resbesideMain.res(see the Deploying guide).
SSR and hydration
- Every module imported by the server entry runs its top-level code in Node. Keep
document/windowaccess insideView.onMount,SSRContext.onClient, orif SSRContext.isClient { … }. - Module-level signals in a server process are shared by all requests; per-request state belongs in components,
Context, or is reset per request (SSRState.clear()for transferred state).
Verify
npx rescriptexits without errors; the build lists each.rescompiled to.res.mjs.- Opening
index.htmlthroughnpx viterenders the root component with no console errors. - A component file can be imported by a test without side effects (nothing mounts on import).
Related
/docs/quick-start— installation and the first component./docs/learn/components— component and props rules./docs/learn/context—Contextin detail./docs/guides/deploying— build and SSR entries./docs/guides/testing— test layout and runner.