This page explains how to debug OCaml programs compiled to JavaScript.
Use -g when compiling and linking OCaml bytecode. Js_of_ocaml will attempt to preserve variable names.
Flag | Description |
| Format JavaScript readably, preserve OCaml variable names |
| Prevent function inlining |
| Add source location comments |
| Generate source map |
For development builds, add to your dune file:
(executable (name main) (modes js) (js_of_ocaml (flags --pretty --source-map)))
Source maps map generated JavaScript back to OCaml sources. With source maps enabled, you can set breakpoints, step through code, and inspect variables directly in your OCaml files.
To enable source maps:
js_of_ocaml --source-map program.byte
This generates program.js and program.js.map.
Open browser developer tools (F12), navigate to the Sources panel, and set breakpoints in your OCaml files (when using source maps) or JavaScript files.
See the Chrome DevTools documentation for details.
Insert breakpoints in your OCaml code using Js.debugger:
let my_function x =
Js_of_ocaml.Js.debugger (); (* Breaks here when devtools are open *)
x + 1Note: Browsers only pause at debugger statements when developer tools are open.
Run your program with Node.js inspector:
node --inspect _build/default/main.bc.js
This prints a URL like:
Debugger listening on ws://127.0.0.1:9229/...
node --inspect or node --inspect-brk (breaks on first line)chrome://inspectTo get JavaScript stack traces attached to OCaml exceptions:
OCAMLRUNPARAM=b=1 node program.js
Or compile with:
js_of_ocaml --enable with-js-error program.byte
See Error handling for details.
Useful settings in Chrome DevTools (Settings > Experiments):