How to use modules with js_of_ocaml?

左心房为你撑大大i 提交于 2019-12-05 05:36:00

I found the solution by trying to understand the makefiles for the official examples.

Here is my Makefile :

OBJS=file1.cmo file2.cmo file3.cmo
NAME=projectname
OCAMLC=ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax -syntax camlp4o

$(NAME).byte: $(OBJS)
        $(OCAMLC) -linkpkg -o $@ $(OBJS)

$(NAME).js: $(NAME).byte
        js_of_ocaml $<

%.cmo: %.ml
        $(OCAMLC) -c $<
...

ocamlbuild keeps a log of the operations it performs. After an ocamlbuild call, look at _build/_log and you will see all the commands that it has invoked, with full arguments etc. That's probably the easiest way for you to figure how to do it by hand.

(Regarding +site-lib assumptions and OPAM, that's something you should report to the authors of the tutorial, they'll want to make sure that it also works for OPAM users.)

It's taken a bunch of experimentation, but I finally figured out how to have ocamlbuild pass the same flags to ocamlfind as ocsigen use in those makefiles. I'm also using js_of_ocaml installed with OPAM.

For my test case, I created a very small example with two files - main.ml and square.ml.

square.ml:

let square x = x * x

main.ml:

let () = (Js.Unsafe.coerce Dom_html.window)##square <- Js.wrap_callback Square.square

The command to build this successfully:

ocamlbuild -use-ocamlfind -pkgs js_of_ocaml,js_of_ocaml.syntax -syntax camlp4o main.byte

This produces identical JS output to my initial test case where the square function was in main.ml. The ocamlbuild log shows exactly what I expect (two calls to ocamldep, two to ocamlc -c, one to ocamlc -linkpkg).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!