Debugging Rust-Generated WebAssembly

    If you don't have debug symbols enabled, then the custom section won'tbe present in the compiled .wasm binary, and stack traces will have functionnames like wasm-function[42] rather than the Rust name of the function, likewasm_game_of_life::Universe::live_neighbor_count.

    When using a "debug" build (aka wasm-pack build —debug or cargo build)debug symbols are enabled by default.

    With a "release" build, debug symbols are not enabled by default. To enabledebug symbols, ensure that you debug = true in the [profile.release] sectionof your Cargo.toml:

    We can use the web-sys crate to get access to the console loggingfunctions:

    Alternatively, hasthe same signature as console.log, but developer tools tend to also captureand display a stack trace alongside the logged message when console.error isused.

    The console_error_panic_hook crate logs unexpected panics to the developerconsole via console.error. Rather than getting cryptic,difficult-to-debug RuntimeError: unreachable executed error messages, thisgives you Rust's formatted panic message.

    All you need to do is install the hook by callingconsole_error_panic_hook::set_once() in an initialization function or commoncode path:

    There is a , so expect this story to improve in the future!

    Nonetheless, debuggers are still useful for inspecting the JavaScript thatinteracts with our WebAssembly, and inspecting raw wasm state.

    References

    If the bug is specific to interactions with JavaScript or Web APIs, then

    If a bug does not involve interaction with JavaScript or Web APIs, then try toreproduce it as a normal Rust #[test] function, where you can leverage yourOS's mature native tooling when debugging. Use testing crates likequickcheck and its test case shrinkers to mechanically reducetest cases. Ultimately, you will have an easier time finding and fixing bugs ifyou can isolate them in a smaller test cases that don't require interacting withJavaScript.