{0 Debugging}

This page explains how to debug OCaml programs compiled to JavaScript.

{1:compiler-flags Compiler flags}

{2 OCaml flags}

Use [-g] when compiling and linking OCaml bytecode. Js_of_ocaml will
attempt to preserve variable names.

{2 Js_of_ocaml flags}

{t
 | Flag | Description |
 | [--pretty] | Format JavaScript readably, preserve OCaml variable names |
 | [--no-inline] | Prevent function inlining |
 | [--debug-info] | Add source location comments |
 | [--source-map] | Generate source map |
}

{2 Dune configuration}

For development builds, add to your dune file:

{v
(executable
 (name main)
 (modes js)
 (js_of_ocaml (flags --pretty --source-map)))
v}

{1:source-maps Source maps}

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:

{v
js_of_ocaml --source-map program.byte
v}

This generates [program.js] and [program.js.map].

{1:breakpoints Breakpoints}

{2 In browser developer tools}

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 {{:https://developer.chrome.com/docs/devtools/javascript}Chrome DevTools documentation} for details.

{2 Programmatic breakpoints}

Insert breakpoints in your OCaml code using {{!Js_of_ocaml.Js.debugger}Js.debugger}:

{@ocaml[
let my_function x =
  Js_of_ocaml.Js.debugger ();  (* Breaks here when devtools are open *)
  x + 1
]}

Note: Browsers only pause at [debugger] statements when developer tools are open.

{1:nodejs Debugging in Node.js}

{2 Using --inspect}

Run your program with Node.js inspector:

{v
node --inspect _build/default/main.bc.js
v}

This prints a URL like:

{v
Debugger listening on ws://127.0.0.1:9229/...
v}

{2 Chrome DevTools for Node.js}

+ Run [node --inspect] or [node --inspect-brk] (breaks on first line)
+ Open Chrome and navigate to [chrome://inspect]
+ Click "Open dedicated DevTools for Node"
+ Your program appears in the Sources panel

{1:stack-traces Stack traces}

{2 Attaching JavaScript backtraces}

To get JavaScript stack traces attached to OCaml exceptions:

{v
OCAMLRUNPARAM=b=1 node program.js
v}

Or compile with:

{v
js_of_ocaml --enable with-js-error program.byte
v}

See {{!page-"errors".stack_traces}Error handling} for details.

{1:devtools-tips Chrome DevTools tips}

Useful settings in Chrome DevTools (Settings > Experiments):

- {b Display variable values inline while debugging} - Shows values next to variables
- {b Resolve variable names} - Maps minified names back to original names

{1 See also}

- {{!page-"errors"}Error handling} - Exception handling between OCaml and JavaScript
- {{!page-"options"}Command line options} - Full list of compiler flags
