File: rev-bindings.wiki

package info (click to toggle)
js-of-ocaml 5.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 32,020 kB
  • sloc: ml: 91,250; javascript: 57,289; ansic: 315; makefile: 271; lisp: 23; sh: 6; perl: 4
file content (44 lines) | stat: -rw-r--r-- 953 bytes parent folder | download | duplicates (2)
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)
}}}