This example shares a toy function between client and server using js_of_ocaml. The function is in common/common.ml.
let greet = function
| `Server -> "Hello..."
| `Client -> "...world!"
The first part of the message is printed by the server, in server/server.eml.ml:
let home =
<html>
<body id="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");
]
The rest is printed by the client, in client/client.ml:
open Js_of_ocaml
let () =
let body = Dom_html.getElementById_exn "body" in
let p = Dom_html.(createP document) in
p##.innerHTML := Js.string (Common.greet `Client);
Dom.appendChild body p
To run the example, do
$ cd example/w-fullstack-jsoo
$ opam install --deps-only --yes .
$ dune build --root . client/client.bc.js
$ mkdir -p static
$ cp _build/default/client/client.bc.js static/client.js
$ dune exec --root . server/server.exe
Then visit http://localhost:8080, and you will see...
See also:
w-one-binary
for bundling assets into a self-contained binary.