1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
= Export OCaml code to JavaScript
The easiest way to export OCaml values (e.g., functions) to JavaScript is to
create a JavaScript object containing all values to export
and to make the object reachable.
<<code language="ocaml"|
open Js_of_ocaml
let _ =
Js.export "myMathLib"
(object%js
method add x y = x +. y
method abs x = abs_float x
val zero = 0.
end)
>>
<<code language="javascript"|
myMathLib.add(3,4)
>>
== Using the Node.js module system
{{{Js.export}}} and {{{Js.export_all}}} will export a value to {{{module.exports}}} if it exists.
{{{
# cat math.ml
open Js_of_ocaml
let _ =
Js.export_all
(object%js
method add x y = x +. y
method abs x = abs_float x
val zero = 0.
end)
# ocamlfind ocamlc -verbose \
-package js_of_ocaml -package js_of_ocaml-ppx \
-linkpkg math.ml -o math.byte
# js_of_ocaml math.byte
# node
# > var math = require("./math.js");
# > math.add(2,3)
}}}
|