Js_of_ocaml

Overview

Js_of_ocaml is a compiler from OCaml bytecode programs to JavaScript. It makes it possible to run pure OCaml programs in JavaScript environments like browsers and Node.js. It is easy to install as it works with an existing installation of OCaml, with no need to recompile any library. It comes with bindings for a large part of the browser APIs.

According to our benchmarks, the generated programs run typically faster than with the OCaml bytecode interpreter. We believe this compiler will prove much easier to maintain than a retargeted OCaml compiler, as the bytecode provides a very stable API.

Js_of_ocaml is composed of multiple packages:

There is also a compiler targeting WebAssembly provided by the wasm_of_ocaml package. See wasm_of_ocaml.

Note: All code examples in this manual use Js_of_ocaml's ppx syntax. It is possible to use Js_of_ocaml purely as a compiler while using a different package (e.g., gen_js_api, brr) to provide bindings to the browser APIs.

Installation

The easiest way to install js_of_ocaml is to use opam:

opam install js_of_ocaml js_of_ocaml-ppx js_of_ocaml-lwt

For alternatives, see Installation.

Usage

Your program must first be compiled using the OCaml bytecode compiler ocamlc. JavaScript bindings are provided by the js_of_ocaml package and the syntax extension by the js_of_ocaml-ppx package:

ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml-ppx \
    -linkpkg -o cubes.byte cubes.ml

Then, run the js_of_ocaml compiler to produce JavaScript code:

js_of_ocaml cubes.byte

Note: Generated JavaScript files are UTF-8 encoded.

With dune

Dune has native support for js_of_ocaml. It supports both standard and separate compilation of JavaScript files. See the dune documentation.

With ocamlbuild (legacy)

Js_of_ocaml provides an ocamlbuild plugin. See js_of_ocaml-ocamlbuild.

Toplevel

You can find an OCaml toplevel running in the browser here. See Building a toplevel to create your own.

Supported features

Most of the OCaml standard library is supported. However:

Extra libraries distributed with OCaml (such as Thread) are not supported in general. However:

Tail call optimization

Tail calls are not optimized in general. However, mutually recursive functions are optimized:

See tailcall optimization for more details.

Effect handlers

Effect handlers are fully supported with the --effects=.. flag. Effect support is disabled by default since effects are not widely used and the generated code can be slower, larger, and less readable. See effect handlers for details.

Data representation

Data representation differs from the usual OCaml runtime:

As a consequence, marshalling, polymorphic comparison, and hashing functions can yield different results:

Note: Float rounding is slightly different between native and JavaScript. Both round to nearest but resolve ties differently: JavaScript resolves ties away from zero while libc resolves ties to even.

See runtime representation for details.