Skip to content

Files

Latest commit

 

History

History

w-fullstack-rescript

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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

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