Skip to content

Project structure

Set up rescript.json, the entry file and a folder layout, and decide where each piece of state should live.

docs/guides/project-structure.md
Raw Markdown

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 write Signal, View and Router instead of Xote.Signal.
  • "subdirs": true compiles every folder under src, 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.res
2View.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, routes
4 styles.css
5 components/ # reusable UI: Header.res, Disclosure.res, Tabs.res
6 pages/ # one file per route: HomePage.res, SettingsPage.res
7 state/ # app-wide signals and the functions that change them

Two ReScript rules shape this:

  • One component per module. @xote.component defines the module's make, so a file like Header.res is the <Header /> component. Small helpers can live as submodules (module Tab = { … } inside Tabs.res, used as <Tabs.Tab />).
  • Module names are global. Folders do not namespace modules, so every file name must be unique across src. Prefer SettingsPage.res over pages/Settings.res next to state/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.res
2@xote.component
3let make = (~label: string, ~children: View.node) => {
4 let isOpen = Signal.make(false)
5
6 <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.res
2let user: Signal.t<option<string>> = Signal.make(None)
3
4let 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.res
2let selected = Context.make(Signal.make(0))
3
4module Tab = {
5 @xote.component
6 let make = (~index: int, ~label: string) => {
7 let current = Context.use(selected)
8 <button
9 class={Signal.get(current) == index ? "tab active" : "tab"}
10 onClick={_ => Signal.set(current, index)}>
11 {label}
12 </button>
13 }
14}
15
16@xote.component
17let 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.res
2@xote.component
3let 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 make per module; move the second into its own file or a submodule.
  • Pointing index.html at Main.res. Vite serves the compiled Main.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.res would be shared by every disclosure. Create it inside make instead.

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

ItemImport / entryFirst stableChanged in 7.2.0Needs the PPX
XoteJSX JSX module, View.mountById, View.mountxote7.0.0—No
@xote.component and its prebuilt PPX binary (xote/ppx/ppx)xote7.1.0——
Context (make, use, provide, Provider)xote, xote/context7.2.0 (new)—No
ReScript compilerrescript 12———

Rules

  1. rescript.json MUST set "jsx": {"version": 4, "module": "XoteJSX"} and list "xote" in "dependencies". Listing "xote" alone is sufficient; its own dependency (rescript-signals) is resolved transitively.
  2. "ppx-flags": ["xote/ppx/ppx"] enables @xote.component. Without it, use @jsx.component with explicit thunks and value components (see /docs/learn/rendering).
  3. "compiler-flags": ["-open Xote"] makes Signal, Computed, Effect, View, Router, … available unqualified. Without it, every file needs open Xote (or qualified names).
  4. "package-specs": {"module": "esmodule", "in-source": true} with "suffix": ".res.mjs" writes Foo.res.mjs next to Foo.res; index.html and Vite reference the compiled .res.mjs, never the .res.
  5. A module's name is its file name, and module names MUST be unique across every source directory ("subdirs": true does not namespace them). Two Dup.res files fail the build: "Duplicate module name: Dup … Rename one of these files."
  6. A module MAY contain only one component (@xote.component or @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.
  7. 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).
  8. The entry module SHOULD only initialise global services (Router.init, SSRState.sync) and mount; components stay importable and testable without side effects.
  9. 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.provide is per subtree.
  10. 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/document unguarded if the module is used on a server.

Where state lives

Who needs itHow many copiesPut it in
One component instanceone per instanceSignal.make in the component body
The whole app (session, cart, settings)onemodule-level signals in state/X.res, with the functions that change them
One subtree, e.g. a tab group or formone per subtree instancea Context whose value is a signal, provided by the subtree's root component (7.2.0)
Data from the serverper viewa Resource in the component that shows it (7.2.0)
Values derived from any of the above—a Computed next to its inputs

API

NameSignatureBehaviour
View.mountById(View.node, string) => unitRenders into the element with that id.
View.mount(View.node, Dom.element) => unitRenders into an element.
Context.make'a => Context.t<'a>Creates a context with a default value.
Context.provide(Context.t<'a>, 'a) => unitIn a component body: provides a value to what that component renders. Raises elsewhere.
Context.useContext.t<'a> => 'aIn 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.res
2View.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, routes
4 styles.css
5 components/ # Header.res, Disclosure.res, Tabs.res
6 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.res
2let 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.res
2@xote.component
3let 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.res
2let selected = Context.make(Signal.make(0))
3
4module Tab = {
5 @xote.component
6 let make = (~index: int, ~label: string) => {
7 let current = Context.use(selected)
8 <button
9 class={Signal.get(current) == index ? "tab active" : "tab"}
10 onClick={_ => Signal.set(current, index)}>
11 {label}
12 </button>
13 }
14}
15
16@xote.component
17let make = (~children: View.node) => {
18 Context.provide(selected, Signal.make(0))
19 <div class="tabs" role="tablist"> {children} </div>
20}

Anti-patterns

  1. Same file name in two folders. Wrong: pages/Settings.res and state/Settings.res. Symptom: "Could not initialize build: Duplicate module name: Settings". Right: SettingsPage.res and SettingsState.res.

  2. 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.

  3. Mounting inside the component's own file. Wrong: View.mountById(<App />, "app") at the bottom of App.res. Symptom: "The module or file App can't be found". Right: mount from Main.res.

  4. Module-level signal for per-instance state. Wrong: let isOpen = Signal.make(false) at the top of Disclosure.res. Symptom: opening one disclosure opens all of them. Right: create the signal inside make.

  5. index.html pointing at a .res file, 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, with rescript watch running.

  6. Context.provide outside 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 own make is <Tabs />.
  • Context.use outside 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": true in rescript.json prefixes module names for published libraries; applications do not need it.
  • Adding routing or SSR later does not change this layout: App.res gains Router.routes, and SSR adds EntryServer.res/EntryClient.res beside Main.res (see the Deploying guide).

SSR and hydration

  • Every module imported by the server entry runs its top-level code in Node. Keep document/window access inside View.onMount, SSRContext.onClient, or if 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 rescript exits without errors; the build lists each .res compiled to .res.mjs.
  • Opening index.html through npx vite renders the root component with no console errors.
  • A component file can be imported by a test without side effects (nothing mounts on import).
  • /docs/quick-start — installation and the first component.
  • /docs/learn/components — component and props rules.
  • /docs/learn/context — Context in detail.
  • /docs/guides/deploying — build and SSR entries.
  • /docs/guides/testing — test layout and runner.