OCaml in the Browser

Ecosystem: Brr (modern browser API bindings), Bonsai (Jane Street UI), Incr_dom, Note.

45.1 js_of_ocaml — compile bytecode to JavaScript

Ecosystem: Brr (modern browser API bindings), Bonsai (Jane Street UI), Incr_dom, Note.

(executable (name main) (modes js) (libraries js_of_ocaml) (preprocess (pps js_of_ocaml-ppx)))
open Js_of_ocaml

let () =
  let doc = Dom_html.document in
  let btn = Dom_html.createButton doc in
  btn##.textContent := Js.some (Js.string "Click me");
  btn##.onclick := Dom_html.handler (fun _ ->
    Dom_html.window##alert (Js.string "Hello from OCaml!"); Js._true);
  Dom.appendChild doc##.body btn

45.2 Melange — OCaml → readable JavaScript (npm ecosystem)

Used with ReasonReact; output is idiomatic JS modules.

(melange.emit (target output) (libraries reason-react) (module_systems commonjs))

45.3 ReasonML

An alternative JavaScript-like syntax for OCaml (same compiler & type system). refmt converts between syntaxes.

let greet = (name) => "Hello, " ++ name;

45.4 wasm_of_ocaml

Compiles OCaml bytecode to WebAssembly (WasmGC), generally faster than JS output, from the js_of_ocaml team.