This example shares a toy function between client and server using ReScript. The function is in common/common.ml. It's in OCaml syntax because the ReScript syntax is not available when compiling to native code:
let greet = function
| `Server -> "Hello..."
| `Client -> "...world!"
As you can probably guess, we are going to print the first part of the message on the server, server/server.eml.ml:
let home =
<html>
<body>
<p><%s Common.greet `Server %></p>
<script src="/static/client.js"></script>
</body>
</html>
let () =
Dream.run
@@ Dream.logger
@@ Dream.router [
Dream.get "/"
(fun _ -> Dream.html home);
Dream.get "/static/**"
(Dream.static "./static");
]
@@ Dream.not_found
...and the rest of the message in the client, client/client.res:
open Webapi.Dom
let () = {
let body = document |> Document.querySelector("body")
switch (body) {
| None => ()
| Some(body) =>
let text = Common.greet(#Client)
let p = document |> Document.createElement("p")
p->Element.setInnerText(text)
body |> Element.appendChild(p)
}
}
To run the whole thing, do
npm install
npm start
Then visit http://localhost:8080, and you will see...
Besides ReScript and Dream, this example also uses
bs-webapi
for DOM manipulation, and esbuild for bundling the
client in ./static/client.js
. The example serves the bundled client using
Dream.static
.
See also:
w-esy
details the server's esy packaging.w-fswatch
sets up a primitive development watcher.w-one-binary
bundles assets into a self-contained binary.f-static
presentsDream.static
.