How to use modules with js_of_ocaml?

本秂侑毒 提交于 2020-01-02 03:14:07

问题


I am currently working on a website project written in OCaml and compiled to javascript using js_of_ocaml. It works pretty well as long as I have only one source file using the command ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax -syntax camlp4o -linkpkg -o file.byte file.ml but I would like to include several modules in my project. How can I do that ?

The other modules are actually a lexer and a parser poduced by ocamllex and menhir. I have read a tutorial on how to use ocamllex and menhir with js_of_ocaml but it makes wrong assumptions on where js_of_ocaml is installed (I installed it with opam) and it uses ocamlbuild and I want to know how to do it by hand without using an automated tool such as ocamlbuild.


回答1:


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 $<
...



回答2:


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.)




回答3:


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).



来源:https://stackoverflow.com/questions/14383500/how-to-use-modules-with-js-of-ocaml

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