How to debug an OCaml program compiled to JavaScript.
Use the right compiler flags
OCaml flags
Make sure to use -g flags when compiling and linking ocaml bytecode. Js_of_ocaml will attempt to preserve variable names.
Js_of_ocaml flags
- --pretty - format the generated JavaScript in a readable way and try to keep OCaml variable names.
- --no-inline - prevent function inlining.
- --debug-info - annotate the JavaScript file with locations from the OCaml sources.
- --source-map - enable source-map support
JavaScript stacktrace
Js_of_ocaml can attach a JavaScript Error that embed the current stacktrace to an OCaml exception. The Error can be attached with Js.Js_error.attach_js_backtrace and extracted using Js.Js_error.of_exn. Un-handled OCaml exception will throw any JavaScript Error attached to them, allowing the JS engine to display the stacktrace nicely.
Js_of_ocaml will attach an Error automatically when raising an OCaml exception (with raise, not with raise_notrace) if Printexc.backtrace_status() = true and either the environment variable OCAMLRUNPARAM is set with b=1 or the program was compiled with --enable with-js-error.
Note that creating JavaScript Errors is costly and can degrade performance a lot. This is the reason why such feature is not enabled by default.
Breakpoint
One can set breakpoints using developers tools (see https://developer.chrome.com/devtools/docs/javascript-debugging). Alternatively, one can set breakpoints programmatically by calling Js.debugger (). Note that browsers will only stop at breakpoints when developers tools are in use.
Source map
Source map is used to map the generated JavaScript code to original sources. After compiling with sourcemap enabled, using developers tools, one can set breakpoints, step through the code, and inspect variable directly in OCaml sources.
About Chrome DevTools
Useful setting Chrome DevTools:
- Display variable values inline while debugging
- Resolve variable names (hidden DevTools Experiments, see http://islegend.com/development/how-to-enable-devtools-experiments-within-google-chrome)