OCaml By Examples



To compile ocaml to javascript, we are going to use the [js\_of\_ocaml](https://ocsigen.org/js_of_ocaml/latest/manual/overview) library. Note that Core is not supported, and so you'll have to use a smaller set of functionnalities of Core: [Core_kernel](https://docs.ocaml.pro/html/OPAM.core_kernel.v0.14.1/index.html).
 (name main)
 (libraries js_of_ocaml core_kernel)
dune supports js\_of\_ocaml out-of-the-box via the `js` mode.
 (modes js)
  (pps js_of_ocaml-ppx)))


open Core_kernel
open Js_of_ocaml

let _ =
  Js.export "myLib"
    (object%js (_self)
you can export polymorphic methods to javascript.
      method add x y = x + y
you can export values as well. Note that exported values and functions must follow the [snake case]().
      val myVal = 3
The [Js\_of\_ocaml.Js](https://ocsigen.org/js_of_ocaml/latest/api/js_of_ocaml/Js_of_ocaml/Js/index.html) module contains javascript types and functions to handle them.
      method hello (name: Js.js_string Js.t) : (Js.js_string Js.t) = 
        let name = Js.to_string name in 
        let hello_name = "hello " ^ name in
        Js.string hello_name
You can also write javascript within your OCaml code. Note that the versino of javascript supported is not recent (no `let` keyword for example).
      method typedArray _ =
         let init_typed_array = Js.Unsafe.js_expr
            {js|(function() {
              var buf = new Uint8Array(2);
              buf[0] = 1;
              return buf;
          let typed_array = Js.Unsafe.fun_call init_typed_array [||] in
          let typed_array = Js_of_ocaml.Typed_array.String.of_uint8Array typed_array in
          String.iter ~f:(fun (x:char) -> printf "%d\n" (int_of_char x)) typed_array


$ opam install js_of_ocaml js_of_ocaml-compiler js_of_ocaml-ppx
To compile to a `.js` file, you need to build with this specific command.
$ dune build ./main.bc.js
You can then use the exported module in javascript.
$ node -e 'const m = require("./_build/default/main.bc.js").myLib; console.log(m.myVal);'
$ node -e 'const m = require("./_build/default/main.bc.js").myLib; m.typedArray()();'
next: rust