dream/example/w-fullstack-rescript
Anton Bachin c5514d72e3 Use esy
2021-04-21 10:49:15 +03:00
..
2021-04-09 16:29:12 +03:00
2021-04-09 12:50:00 +03:00
2021-04-19 00:36:48 +03:00
2021-04-09 12:50:00 +03:00
2021-04-09 12:50:00 +03:00
2021-04-09 12:50:00 +03:00
2021-04-21 10:49:15 +03:00
2021-04-21 10:49:15 +03:00
2021-04-21 10:49:15 +03:00

w-fullstack-rescript


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 for the server side:

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

Full-stack greeting


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:


Up to the example index